[LeetCode]Search Insert Position

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

遍历的方法当然能做,但是时间复杂度O(n)。

二分查找可以将时间复杂度降为O(logn)。

 1 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4         if(nums.size()==0 || target<=nums[0]) return 0;
 5         int n = nums.size();
 6         if(target==nums[n-1]) return (n-1);
 7         if(target>nums[n-1]) return n;
 8         int i=0,j=n-1;
 9         while((j-i)!=1)
10         {
11             int temp = (i+j)/2;
12             if(nums[temp]==target) return temp;
13             else if((nums[temp]<target))
14             {
15                 i = temp;
16             }
17             else
18             {
19                 j=temp;
20             }
21         }
22         return (i+1);
23     }
24 };
原文地址:https://www.cnblogs.com/Sean-le/p/4786868.html