Thursday, January 3, 2013

[LeetCode] 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
» Solve this problem

[解题思路]
跟经典的二分查找相比,只是多了一个条件:
if(mid>left && A[mid]>target && A[mid-1]<target)


[Code]
1:  int searchInsert(int A[], int n, int target) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      int l=0, r=n-1;  
5:      while(l<=r)  
6:      {  
7:        int mid = (l+r)/2;  
8:        if(A[mid] == target) return mid;  
9:        if(mid>l && A[mid]>target && A[mid-1]<target ) return mid;  
10:        if(A[mid] > target)  
11:        {  
12:          r= mid-1;  
13:        }  
14:        else  
15:        {  
16:          l=mid+1;  
17:        }        
18:      }  
19:      return l;  
20:    }  







No comments: