leetcode: Search Insert Position
http://oj.leetcode.com/problems/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
思路:
用二分法,如果能找到target,直接在当前位置插入即可,如果不能找到,根据中断循环时A[mid]的值,有以下两种情况:
- A[mid] < target:根据二分法的原则,mid位置上的数肯定是最后一个小于target的数,那么插入位置就是mid + 1。
- A[mid] > target:同理,mid位置上的数肯定是第一个大于target的数,那么插入位置就是mid。
1 class Solution { 2 public: 3 int searchInsert(int A[], int n, int target) { 4 int start = 0, end = n - 1, mid; 5 6 while (start <= end) { 7 mid = (start + end) / 2; 8 9 if (A[mid] == target) { 10 return mid; 11 } 12 else if (A[mid] < target) { 13 start = mid + 1; 14 } 15 else { 16 end = mid - 1; 17 } 18 } 19 20 return (A[mid] > target) ? mid : mid + 1; 21 } 22 };