原题网址:https://leetcode.com/problems/two-sum/
解题思路:这题思路和插入排序非常相似,我就是根据插入排序思想写的,代码比较简单
public static int searchInsert(int[] nums, int target) {
// int len = nums.length;
int i;
for(i = nums.length - 1; i >= 0; i--){
if (target > nums[i]){
return i+1;
}
}
return 0;
}
最优解:采用的是二分法,挺好的思路,非常快~!!
public int searchInsert(int[] A, int target) {
int low = 0, high = A.length-1;
while(low<=high){
int mid = (low+high)/2;
if(A[mid] == target) return mid;
else if(A[mid] > target) high = mid-1;
else low = mid+1;
}
return low;
}