leetcode 35: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,即

if(low>high) return -1;

现在返回的就是low或者是high了,也是比较简单,时间复杂度:O(lgn)

class Solution {
public:
	int searchInsert(vector<int>& nums, int target) {
		int size = nums.size();
		if (size == 0) return 0;
		return binary(nums, 0, size - 1, target);
	}

	int binary(vector<int>&array, int low, int high, int key)
	{
		if (low > high)
		{
			return low;
		}
		int mid = (low + high) / 2;

		if (array[mid] == key)
			return mid;
		else if (array[mid] < key)
			return binary(array, mid + 1, high, key);
		else
			return binary(array, low, mid - 1, key);
	}
};


你可能感兴趣的:(leetcode 35:Search Insert Position)