LeetCode - search-in-rotated-sorted-array-ii

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/toward_south/article/details/89448969

题目:

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.

题意:

在    interleaving-stringsearch-in-rotated-sorted-array 基础上多了重复元素罢了

解题思路:

还是可以直接暴力搜索法解决    -- 复杂度O(n):

    /*
	 * 暴力解决
	 */
	public static boolean search(int[] A, int target) {
		if(A.length <= 0 || A == null) {
			return false;
		}
		for(int i = 0 ; i< A.length; i++) {
			if(target == A[i]) {
				return true;
			}
		}
		return false;
        
    }

下面还是使用 题1 的折半查找来解决  平均还是O(logn)

扫描二维码关注公众号,回复: 6108669 查看本文章

先分析这题,这题是可以允许出现重复元素的,所以当他旋转的时候,如果存在重复元素我们是无法判断哪边是有序的。

所以这里可以当中间元素和边缘元素相等时,我们可以让边缘的index向中点靠拢,直到中点的值和边缘的值不相等就行

Java代码:

/*
	 * 折半查找
	 */
	public static boolean search2(int[] A, int target) {
		if(A == null || A.length <= 0) {
			return false;
		}
        int low = 0;
        int high = A.length-1;
        while(low <= high) {
        	int mid = (low + high)/2;
        	//在中间的情况
        	if(A[mid] == target) {
        		return true;
        	}
        	//mid-high为升序状态
        	if(A[mid] < A[high]) {
        		if(target > A[mid] && target <= A[high]) {
        			low = mid + 1;
        		}
        		else {
        			high = mid -1;
        		}
        	}
        	//low - mid是有序的
        	else if(A[mid] > A[high]){
        		if(target >= A[low] && target < A[mid] ) {
        			high = mid - 1;
        		}
        		else {
        			low = mid + 1;
        		}
        	}
        	else {
        		high--;
        	}
        	
        }
        
        return false;
    }

猜你喜欢

转载自blog.csdn.net/toward_south/article/details/89448969