35. Search Insert Position 寻找插入位置

xiaoxiao2021-02-28  22

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.

Example 1:

Input: [1,3,5,6], 5 Output: 2

Example 2:

Input: [1,3,5,6], 2 Output: 1

Example 3:

Input: [1,3,5,6], 7 Output: 4

Example 1:

Input: [1,3,5,6], 0 Output: 0

思路:利用二分查找

class Solution { public: int searchInsert(vector<int>& nums, int target) { int begin = 0; int end = nums.size() - 1; int index = -1; while(index == -1) { int mid = (begin + end) / 2; if(nums[mid] == target) return mid; else if(nums[mid] < target) { // target 放在nums的最后,或是target在nums[mid]和nums[mid + 1]之间 if(mid + 1 == nums.size() || nums[mid + 1] > target) index = mid + 1; begin = mid + 1; } else { // target 放在nums的最前面,或是target在nums[mid - 1]和nums[mid]之间 if(mid == 0 || nums[mid - 1] < target) index = mid; end = mid - 1; } } return index; } };

转载请注明原文地址: https://www.6miu.com/read-2249979.html

最新回复(0)