Search Insert Position @leetcode

#二分我好乱

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         if(n == 0) return n;
 7         if(target < A[0]) return 0;
 8         else if(target > A[n-1]) return n;
 9         else if(n == 2)
10         {
11             if(target == A[0]) return 0;
12             if(target <= A[1]) return 1;
13         }
14         int b,e;
15         b=0;e=n-1;
16         while(b+1<e)
17         {
18             if(A[b] == target) return b;
19             if(A[e] == target) return e;
20             if(A[(e+b)/2]>target)
21                 e=(e+b)/2;
22             else if(A[(e+b)/2]<target)
23                 b=(e+b)/2;
24             else
25                 return (e+b)/2;
26         }
27         return e;
28     }
29 };

#nb版

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         int left = 0, right = n;
 7         int mid = 0;
 8         while (left < right) {
 9             mid = left + (right - left) / 2;
10             if (A[mid] > target) {
11                 right = mid;
12             } else if (A[mid] < target) {
13                 left = mid + 1;
14             } else {
15                 return mid;
16             }
17         }
18         return left;
19     }
20 };

 

 

posted @ 2013-11-14 17:51  沙茶面  阅读(135)  评论(0编辑  收藏  举报