搜索插入位置

题目

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 1:

输入: [1,3,5,6], 5 输出: 2 示例 2:

输入: [1,3,5,6], 2 输出: 1 示例 3:

输入: [1,3,5,6], 7 输出: 4 示例 4:

输入: [1,3,5,6], 0 输出: 0

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/search-insert-position 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


解决方法

思路
  1. 第一想法就是直接遍历
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int searchInsert(int[] nums, int target) {
//     int i = 0;
//     for (int j = 0; j < nums.length; j++){
//         if (nums[j] == target || nums[j] > target){
//             break;
//         }
//         i++;
//     }
//     return i;
// }

  1. 第二个方法是看了解题才想起来,这可以使用二分法。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public int searchInsert(int[] nums, int target) {
	int left = 0;
	int right = nums.length - 1;

	while(left <= right){
		int mid  = (left + right) / 2;
		
		if (nums[mid] == target){
			return mid;
		}
		if (nums[mid] > target){
			right = mid - 1;
		}else{
			left = mid + 1;
		}
	}

	return left;
}
  • 需要注意,当新插入的值在最左侧和最右侧的情况,也就是 left == right 的情况的返回值。
  • 最左侧的时候返回left,也就是0;
  • 最右侧的时候返回left,此时的left是最右侧索引值 + 1;