zoukankan      html  css  js  c++  java
  • 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.

    思路:1.在做完findMin之后,对做rotated很有启发。  2.以前写的花了40ms,具体什么方法还没回顾。 我终于懂了rotated是啥了。轮转暗暗

    注意 findmin中while(a<b); rotated binary search中while(a<=b); Σ( ° △ °|||)︴介个好捉急。待我,想想怎么把while里面带不带=的问题解决掉。

    findMin里while(a<b)不带等号原因: if a==b, it means only one element in array, so a is the min, don't need to find again.

    rotated binary search里while(a<=b)带等号的原因, target need to compare with num[a] or num[b], so compare is still need!

    class Solution {
    public:
    /*find the min, then use binary search to find target*/
        int search(int A[], int n, int target) {
            int a=0,b=n-1,mid=0;
            while(a<b){
                mid = (a+b)/2;
                if(A[mid]>A[b]) a=mid+1;
                else b=mid;
            }
            int indexOfMin = a;
            /*-----binary search----*/
            int offset=indexOfMin; //if not rotated, min is the start element
            a=0;b=n-1;
            while(a<=b){
                mid=(a+b)/2;
                int realMid=(mid+offset)%n; 
                if(target == A[realMid]) return realMid;
                else if(target<A[realMid]) b=mid-1;
                else a=mid+1;
            }
            return -1;
            
        }
    
    };

    算法里巧妙的地方在于  使用offset寻找realMid, target与A[realMid]比较,判断下一轮计算的realMid应该更小,还是更大。

  • 相关阅读:
    Linux 之 文件压缩解压
    Linux 之 文件搜索命令
    Linux 之 文件内容查看
    Linux 之 Vim常用命令
    Linux 之 CentOS练习
    CentOS找不到想要的镜像版本?
    Swoole 简单学习(2)
    Swoole 简单学习
    svn的简单知识
    8、16、32-BIT系列单片机区别与特点
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4332101.html
Copyright © 2011-2022 走看看