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

Search in Rotated Sorted Array I && II

时间:2015-01-28 18:04:40      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

对翻过一次的排序数组二分查找,要利用好已排序这个条件

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

II中允许重复数字,碰到相等的向前移。

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


Search in Rotated Sorted Array I && II

标签:

原文地址:http://blog.csdn.net/sina012345/article/details/43232267

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