LeetCode Search in Rotated Sorted Array

class Solution {
public:
    int search(int A[], int n, int target) {
        if (n < 1) return -1;
        
        int left = -1, right = n, mid;
        int last = A[n-1];
        while (left + 1 < right) {
            mid = (right + left) / 2;
            if (A[mid] < last) {
                right = mid;
            } else if (A[mid] > last) {
                left = mid;
            } else {
                right = mid; // only when n == 1
            }
        }
        
        if (last > target) {
            right = n;
        } else if (last < target){
            left = -1;
        } else {
            return n-1;
        }
        while(left + 1 < right) {
            mid = (right + left) / 2;
            if (A[mid] < target) {
                left = mid;
            } else if (A[mid] > target) {
                right = mid;
            } else {
                return mid;
            }
        }
        return -1; 
    }
};

先用二分找出分界元素,然后根据所要搜索数值和最后一个数的大小关系确定在那一段内搜索。

第二轮:

对于重复数字数组可以采用稍微简单一点的方法,不用先特地求出分界:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int len = nums.size();
        int lo = 0;
        int hi = len - 1;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[mid] >= nums[lo]) {
                if (nums[lo] <= target && nums[mid] >= target) {
                    hi = mid;
                } else {
                    lo = mid + 1;
                }
            } else {
                if (nums[mid] <= target && nums[hi] >= target) {
                    lo = mid + 1;
                } else {
                    hi = mid;
                }
            }
        }
        if (lo < len && nums[lo] == target) {
            return lo;
        }
        return -1;
    }
};

当有重复数字是`nums[mid] >= nums[lo]`判断就会有问题了

posted @ 2014-04-23 22:50  卖程序的小歪  阅读(151)  评论(0编辑  收藏  举报