Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
一刷:
- 给你的数组是一个顺序值,先判断目标值是否大于最后一个数值,如果是则插入值就是最后一个数字的索引。
2.循环数组的每个元素,如果目标值大于或等于这个元素的时候就替换这个元素的位置,其索引就是这个值。
public static int searchInsert(int[] nums, int target) {
int index = 0;
if (target >= nums[nums.length - 1]) {
return nums.length;
}
for (int i = 0; i < nums.length; i++) {
if (target <= nums[i]) {
index = i;
break;
}
}
return index;
}
二刷:一刷循环的话可能会遍历整个数组,所以想到了二分法。
- 定义两个变量
low
,high,分别是数组的第一个元素和最后一个元素的索引
2.循环取中间索引mid
的值,如果目标值和中间索引值相等,即返回中间值的索引
3.如果大于索引值,low=mid+1
,进入下次循环
4.如果小于索引值,high=mid-1
,进入下次循环
public static int searchInsert1(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}