奔跑的小河
Talk is cheap. Show me the code.

导航

 
题目:Follow up for ”Search in Rotated Sorted Array”: What if duplicates are allowed?
            Would this affect the run-time complexity? How and why?

            Write a function to determine if a given target is in the array.

分析:与上题不同的是允许数组中有重复的元素,这个时候就只需要特殊处理这个相同的元素即可。

代码:

class Solution2{
public:
	int search(int A[], int n, int target) {
		int first =0 ;int last = n;
		while(first != last){
			int mid = (first + last)/2;
			if (A[mid] == target){
				return mid;
			}

			if (A[first] < A[mid]){ //first到mid之间元素内有序,那么就在该段内尝试查找
				//判断target是否在范围之内
				if (A[first]<=target && target < A[mid]){
					last = mid;
				}else{
					first = mid + 1;
				}
			}else if(A[first] > A[mid]){ //first到mid之间元素无序,那么这时后半部分有序,尝试查找。
				//判断target是否在范围之内
				if (A[mid] < target && target <= A[last - 1]){
					first = mid + 1;
				}else{
					last = mid;
				}
			}else{//处理重复元素的情况
				first++ ;//直接略过该元素
			}
		}
		return -1;
	}
};


posted on 2015-04-26 17:40  奔跑的小河  阅读(121)  评论(0编辑  收藏  举报