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




class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        lo = 0
        hi = len(nums) - 1
        while lo <=hi:
            mid = lo + (hi-lo)//2
            if target < nums[mid]:
                hi = mid - 1
            elif target > nums[mid]:
                lo = mid + 1
            else:
                return mid
        return lo

 




开区间

 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;
 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;
13             } else {
14                 high = mid;
15                 //return mid;
16             }
17         }
18         return low;
19     }
20 };

 

 闭区间

 

 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  乐乐章  阅读(270)  评论(0编辑  收藏  举报