您的位置:首页 > 其它

LeetCode 81 Search in Rotated Sorted Array II

2014-07-02 18:42 375 查看
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.

思路:折半查找+部分顺序遍历

public class Solution {
	public boolean search(int[] A, int target) {
		if (A == null || A.length == 0)
			return false;

		int left = 0;
		int right = A.length - 1;
		int mid;
		while (left <= right) {
			mid = (left + right) / 2;
			if (target == A[mid])
				return true;

			if (A[mid] < A[right]) {
				if (target <= A[right] && target > A[mid])
					left = mid + 1;
				else
					right = mid - 1;
			} else if(A[mid] > A[right]){
				if (A[left] <= target && target < A[mid])
					right = mid - 1;
				else
					left = mid + 1;
			}else{
				while(left<=right){
					if(A[left]==target) return true;
					left++;
				}
				return flase;
			}
		}
		return false;
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: