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.

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

Exampl 4:

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

 

 闭区间

 

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

 

 

 

 

posted @ 2018-05-03 22:20  乐乐章  阅读(272)  评论(0编辑  收藏  举报