[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


这个和http://blog.csdn.net/xy010902100449/article/details/48806571差不多类似,采用二分法查找即可。

int searchInsert(int* nums, int numsSize, int target)
{
	if(numsSize <= 0)
		return 0;
	int low = 0;
	int high = numsSize-1;
	int mid;
	int flag = 0;
	/*1.判断数组是增序还是降序*/
	if(nums[0] < nums[numsSize-1]) {
		flag = 1;
	}
	else if(nums[0] == nums[numsSize-1]) {
		
		if(target <= nums[0])
			return 0; 
		else
			return numsSize;
	}
	else {
		flag = 0;
	}
	
	/*2.二分法查找插入的位置*/
	if(flag) {
		
		while(low <= high) {
			mid = low+(high-low)/2;
			if(target < nums[mid]) { 
				high = mid-1;
			}
			else if(target == nums[mid]) {
				return mid;
			}
			else {
				low = mid + 1;
			}
				
		}
	}
	else {
		
		while(low <= high) {
			mid = low+(high-low)/2;
			if(target < nums[mid]) { 
				low = mid + 1;
			}
			else if(target == nums[mid]) {
				return mid;
			}
			else {
				high = mid - 1;
			}
			
		}
		
	}
		
	return low;   
}


你可能感兴趣的:(LeetCode,二分法)