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

解题分析:

    这道题的意思是在一个排序的数组中寻找target值,如果该值在数组中,就返回该位置的下标;如果该值没有在数组中,就返回该值应该在这个数组(已排序)的位置的下标。

    这道题最简单的做法是:遍历一遍数组,找到该值就返回下标;没有找到该值,就返回第一个比该值大的位置的下标。时间复杂度为O(n)

  O(logn)的算法是二分查找法:找到中间位置mid,mid如果比该值大,那么说明该值在mid的左边,在左边的区间再次进行二分查找;mid如果比该值小,那么说明该值在mid的右边,在右边的区间再次进行二分查找;如果mid等于该值,就返回mid的下标。

边界条件:当搜素区间只有一个元素的时候,如果该元素大于等于该值,就返回该元素的下标;如果该元素小于该值,就返回该元素下标+1的位置。根据思路,参考代码为:

class Solution {
public:
	int searchInsert(int A[], int n, int target) {
		int low = 0,high = n-1;
		int mid;
		while(low <= high)
		{
			mid = (low + high)/2;
			if(A[mid] == target)
				return mid;
			else if(A[mid] < target)
				low = mid + 1;
			else
				high = mid - 1;
			//如果low==high时,都没找见,就说明数组中没有该元素
			//该元素应该在此时的low位置
		}
		return low;
	}
};


猜你喜欢

转载自blog.csdn.net/qiana_/article/details/80937476