Search in Rotated Sorted Array

来源:互联网 发布:淘宝越墙vans是正品吗 编辑:程序博客网 时间:2024/06/03 22:29

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.

思路:典型的排序查找,但需要先确定两个排序搜索的范围。但是这样时间复杂度就会为O(2N), 所以应该有能简单的方法。

class Solution {public:    int search(int A[], int n, int target) {        if (A == NULL) {            return NULL;        }                int left = 0;        int right = n - 1;        int mid;                while (left <= right) {            mid = left + (right - left) / 2;            if (target == A[mid]) {                return mid;            }            else if (A[mid] >= A[left]) {  //对于只有两个元素的                // left side is sorted                if (target < A[mid] && target >= A[left]) { //=号                    right = mid - 1;                }                else {                    left = mid + 1;                }            }            else if (A[mid] < A[right]) {                // right side is sorted                if (target > A[mid] && target <= A[right]) { //=号                    left = mid + 1;                }                else                 {                    right = mid - 1;                }            }        }        return -1;    }};


0 0
原创粉丝点击