导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-35.Search Insert Position

题目

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

翻译

给出一个有序数组,和一个target值。如果找到target则返回其index,如果找不到,则返回它应当插入的index。
你可以认为数组中无重复元素。
这里有一些例子。
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

考察对二分查找的深入理解。设立low和high,不断取中判断。当找到元素时直接返回,若找不到,则退出循环时,一定是high比low小1,并且 nums[high] < target < nums[low],所以直接返回low即可:

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0, high = nums.length - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (nums[mid] < target) low = mid + 1;
else if (nums[mid] > target) high = mid - 1;
else return mid;
}
return low;
}
}