[LeetCode] Search Insert Position

http://oj.leetcode.com/problems/search-insert-position/

简单二分.

 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 09:42  NextLife  阅读(145)  评论(0)    收藏  举报