看了其他人的解答,还可以使用二分法查找,会提高程序效率
class Solution {
public int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= target) {
return i;
}
}
return nums.length;
}
}
又写了二分法
class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0;
int high = nums.length;
int mid = 0;
while (low < high) {
mid = low + (high - low)/2;
if (nums[mid] > target) {
high = mid;
}
else if(nums[mid] < target){
low = mid+1;
}
else {
return mid;
}
}
return low;
}
}