码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Search in Rotated Sorted Array II

时间:2014-05-15 09:29:52      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

bubuko.com,布布扣
class Solution {
public:
    bool search(int A[], int n, int target) {
        if (n < 1) return false;
        int pre = A[0];
        int wpos = 1, rpos = 1;
        while (rpos < n) {
            if (A[rpos] == pre) {
                rpos++;
            } else {
                pre = A[wpos++] = A[rpos++];
            }
        }
        n = wpos;
        
        int sep = A[n-1];
        int left = -1, right = n;
        while (left + 1 < right) {
            int mid = (left + right) / 2;
            if (sep > A[mid]) {
                right = mid;
                sep = A[mid];
            } else if (sep < A[mid]) {
                left = mid;
            } else {
                right = mid;
                break;
            }
        }
        return binary_search(A, right, target) || binary_search(A + right, n - right, target);
    }
    
    bool binary_search(int *a, int n, int target) {
        int left = -1, right = n;
        while (left + 1 < right) {
            int mid = (left + right) / 2;
            if (a[mid] > target) {
                right = mid;
            } else if (a[mid] < target) {
                left = mid;
            } else {
                return true;
            }
        }
        return false;
    }
};
bubuko.com,布布扣

多了一步去重的步骤,复杂度没什么变化,只是这样做修改了输入数据

LeetCode Search in Rotated Sorted Array II,布布扣,bubuko.com

LeetCode Search in Rotated Sorted Array II

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/lailailai/p/3729037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!