lintcode63- Search in Rotated Sorted Array II- medium

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.

Example

Given [1, 1, 0, 1, 1, 1] and target = 0, return true.
Given [1, 1, 1, 1, 1, 1] and target = 0, return false.

 
九章算法上的回答:

// 这个问题在面试中不会让实现完整程序
// 只需要举出能够最坏情况的数据是 [1,1,1,1... 1] 里有一个0即可。
// 在这种情况下是无法使用二分法的,复杂度是O(n)
// 因此写个for循环最坏也是O(n),那就写个for循环就好了
// 如果你觉得,不是每个情况都是最坏情况,你想用二分法解决不是最坏情况的情况,那你就写一个二分吧。
// 反正面试考的不是你在这个题上会不会用二分法。这个题的考点是你想不想得到最坏情况。

真的要写一个解决并不是最坏情况的话,还是和find the minimum II一个策略,先把end移到倒数第一个不等于开头的数再开始普通的。】

public class Solution {
    /*
     * @param A: an integer ratated sorted array and duplicates are allowed
     * @param target: An integer
     * @return: a boolean 
     */
    public boolean search(int[] A, int target) {
        // write your code here
        if (A == null || A.length == 0){
            return false;
        }

        int start = 0;
        int end = A.length - 1;
        if (A[end] == target){
            return true;
        }
        
        while (end > 0 && A[end] == A[start]){
            end--;
        }
        
        int CmpTgt = A[end];
        if (target == CmpTgt){
            return true;
        } else if (target > CmpTgt){
            while (start + 1 < end){
                int mid = start + (end - start) / 2;
                if (A[mid] > target){
                    end = mid;
                }else if (A[mid] > CmpTgt){
                    start = mid;
                }else {
                    end = mid;
                }
            }
        } else{
            while (start + 1 < end){
                int mid = start + (end - start) / 2;
                if (A[mid] > CmpTgt){
                    start = mid;
                } else if (A[mid] > target){
                    end = mid;
                } else {
                    start = mid;
                }
            }
        }

        if (A[start] == target || A[end] == target){
            return true;
        }

        return false;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7586169.html