对撞指针
2018-10-02 本文已影响0人
少寨主的互联网洞察
对撞指针.png
- 程序:
package com.cqu.test1;
public class Solution2 {
public static int[] twoSum(int[] nums,int target) {
if(nums==null||nums.length==0) {
return null;
}
int i=0;
int j=nums.length-1;
while(i<j) {
int x=nums[i]+nums[j];
if(x<target) {
++i;
}else if(x>target) {
j--;
}else {
return new int[] {i+1,j+1};
}
}
return null;
}
public static void main(String[] args) {
int[] A= {0,2,5,4,6,3,7,8};
int[] result=twoSum(A, 9);
if(result!=null) {
System.out.println(result[0]+" "+result[1]);
}
}
}
- 结果
7 2