Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

示例 1:

  1. Input: nums = [1,3,5,6], target = 5
  2. Output: 2

示例 2:

  1. Input: nums = [1,3,5,6], target = 2
  2. Output: 1

示例 3:

  1. Input: nums = [1,3,5,6], target = 7
  2. Output: 4

示例 4:

  1. Input: nums = [1,3,5,6], target = 0
  2. Output: 0

示例 5:

  1. Input: nums = [1], target = 0
  2. Output: 0

提示:

  • 1 ≤ nums.length ≤ 10;
  • -10 ≤ nums[i] 10;
  • nums contains distinct values sorted in ascending order.
  • -10 ≤ target ≤ 10

思路

题目要求在O(log n)的时间复杂度下找到给定值的下表,这是一个二分查找的题目。

二分查找有两个编码思路:

  • 第一个是Cpp代码所展示的。我们定义的搜索空间是[left, right]左闭右闭区间,注意我们的while(left <= right)right = mid - 1;
  • 第二个是Rust代码锁展示的。我们定义的搜索空间是[left, right)左闭右开区间,注意我们的whilie(left < right)right = mid;

代码

Cpp:

  1. class Solution {
  2. public:
  3. int searchInsert(vector<int>& nums, int target) {
  4. if( nums.size() == 1 ) {
  5. if( target > nums[0] ) return 1;
  6. return 0;
  7. }
  8. int left = 0, right = nums.size() - 1;
  9. while( right >= left ) {
  10. int mid = left + (right - left) / 2;
  11. if( nums[mid] == target )
  12. return mid;
  13. else if( nums[mid] < target )
  14. left = mid + 1;
  15. else
  16. right = mid - 1;
  17. }
  18. // Target not found, insert it
  19. return left;
  20. }
  21. };

Rust:

  1. impl Solution {
  2. pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
  3. if nums.len() == 1 {
  4. if target > nums[0] {
  5. return 1;
  6. }
  7. return 0;
  8. }
  9. let mut left = 0;
  10. let mut right = nums.len();
  11. while right > left {
  12. let mut mid = left + (right - left) / 2;
  13. if nums[mid] > target { right = mid; }
  14. else if nums[mid] < target { left = mid + 1; }
  15. else { return mid as i32; }
  16. }
  17. // Target not found, insert it
  18. left as i32
  19. }
  20. }