Search in Rotated Sorted Array II

来源:互联网 发布:淘宝联盟导购推广名称 编辑:程序博客网 时间:2024/06/05 19:10

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.

和上一题一模一样,唯一要注意的就是如果三个点都相等:A[m] == A[l] == A[h],那么就线性搜索:


    public boolean search(int[] A, int target) {        return helper(A, target, 0, A.length-1);    }        boolean helper(int[] A, int target, int l, int h) {        if (l > h) {            return false;        }                int m = l + (h-l)/2;        if (A[m] == target) {            return true;        }        if (A[l] == A[m] && A[m] == A[h]) {            for (int i = l; i <= h; i++) {                if (A[i] == target) {                    return true;                }            }            return false;        }        if (A[l] <= A[m]) { // pivot is in the right            if (A[l] <= target && target < A[m]) {                return helper(A, target, l, m-1);            } else {                return helper(A, target, m+1, h);            }        } else { // pivot is in the left            if (A[m] < target && target <= A[h]) {                return helper(A, target, m+1, h);            } else {                return helper(A, target, l, m-1);            }        }    }


0 0
原创粉丝点击