zoukankan      html  css  js  c++  java
  • Search in Rotated Sorted Array 分类: Leetcode(线性表) 2015-01-29 10:23 58人阅读 评论(0) 收藏

    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.

    二分查找的推广,需要增加判断条件,为方便举例我们假设要找的数字为3,先用mid把数列分为两种情况,再讨论两种情况的子情况

    mid = first+ ( end - first)/2;

    if ( A[mid ] == target ) return mid;(找到终止)

    if ( A[first] <=  A[mid])   (这个时候还得考虑两种情况,1 2 3 4 5 6 7 8 9 和 5 6 7 8 9 1 2 3 4)

    {

    if( A[first] < target && target < =A[mid])

    { end=mid ; }

    else

    { first= mid+1; }

    }

    else   ./A[first] > A[mid]) (7 8 9 1 2 3 4 5 6  和  9 1 2 3 4 5 6 7 8)

    {

    if(A[mid] < target && target <=A[end-1])

    { first = mid+1 }

    else

    { end = mid; }

    }

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


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    HDU 5492 Find a path
    codeforce gym 100548H The Problem to Make You Happy
    Topcoder SRM 144 Lottery
    codeforce 165E Compatible Numbers
    codeforce gym 100307H Hack Protection
    区间DP总结
    UESTC 1321 柱爷的恋爱 (区间DP)
    HDU 4283 You Are the One (区间DP)
    HDU 2476 String painter (区间DP)
    UESTC 426 Food Delivery (区间DP)
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656963.html
Copyright © 2011-2022 走看看