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

 

思路:

1. 二分法变形, 最讨厌的题目, 总是搞不清该返回 low 还是 high

2. 若是真的要解释话. 最终 low == high, 这个时候, Mid = low = high. 假如 A[mid]>target, 那么插入位置就是 mid 处, 返回 low, OK. 假如 A[mid] < target, 那么 low = mid+1, 仍然返回 low

3. 二分法的题目, 总是不能随心所欲

 

代码:

class Solution {

public:

    int searchInsert(int A[], int n, int target) {

		return bSearch(A, n, target);

    }

	int bSearch(int A[], int n, int target) {

		int low = 0, high = n-1;

		while(low <= high) {

			int mid = (low+high)>>1;

			if(A[mid] == target) 

				return mid;

			else if(A[mid] > target) 

				high = mid-1;

			else

				low = mid+1;

		}

		if(high < 0) return 0;

		if(low >= n) return n;

		return low;

	}

};

  

你可能感兴趣的:(LeetCode)