[LeetCode] Search in Rotated Sorted Array 1 / 2

Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

 

 

class Solution {
public:
    int search(int A[], int n, int target) {
        if (A == NULL || n <= 0) return false;
        int first = find_first(A, n);
        
        int left = first, right = first + n - 1;
        int *a = A;
        while (right - left > 1) {
            int mid = left + (right - left) / 2;
            if (a[mid%n] == target) return mid%n;
            else if (a[mid%n] > target) right = mid;
            else left = mid;
        }
        if (a[right%n] == target) return right %n;
        if (a[left%n] == target) return left%n;
        return -1;
    }
    
    int find_first(int *a, int n) {
        if (a == NULL || n <= 0) return -1;
        int left = 0, right = n - 1;
        while (right - left > 1) {
            int mid = left + (right - left) / 2;
            if (a[mid] > a[right]) 
                left = mid;
            else if (a[mid] < a[left]) 
                right = mid;
            else
                break;
        }
        if (left < right) {
            return (a[left] < a[right] ? left : right);
        } else 
            return -1;
    }
};

 

Search in Rotated Sorted Array II Apr 20 '12 4077 / 10753

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.

 

class Solution {
public:
    bool search(int A[], int n, int target) {
        int s = find1st(A, n, target);
        int l = s, r = s + n - 1;
        auto a = A;
        while (l < r) {
            if (r - l == 1) break;
            int mid = (r + l) / 2;
            if (a[mid%n] <= target) l = mid;
            else if (a[mid%n] > target) r = mid;
        }
        if (a[l%n] == target || a[r%n] == target) return true;
        else return false;
    }
    
    int find1st(int A[], int n, int target) {
        int l = 0, r = n - 1;
        auto a = A;
        while (l < r && a[l] == a[r]) l++;
        if (a[l] < a[r]) return l;
        while (l < r) {
            if (r - l == 1) break;
            int mid = (r + l) / 2;
            if (a[mid] == a[l]) l = mid;
            else if (a[mid] > a[l]) l = mid;
            else if (a[mid] < a[l]) r = mid;
        }
        if (a[l] < a[r]) return l;
        else return r;
    }
};

 

你可能感兴趣的:(LeetCode)