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
public class Solution {
public int searchInsert(int[] nums, int target) {
int min = 0;
int max = nums.length-1;
while (min <= max) {
int mid = (min+max)/2;
if (target < nums[mid]) {
max = mid-1;
} else if (target > nums[mid]) {
min = mid+1;
} else {
return mid;
}
}
return min;
}
}
本文介绍了如何在一个已排序的数组中查找目标值的正确插入位置,确保数组保持有序。通过实现二分查找算法,我们能够高效地找到目标值所在的位置或其应该插入的位置。
451

被折叠的 条评论
为什么被折叠?



