论坛首页 入门技术论坛

[LeetCode] Search in Rotated Sorted Array

浏览 1186 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-12  

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;
    }
};

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics