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

    三个招:前两个很简单,巧妙地是第三个。

    //方法一:分批次二分查找 ;查找出分割点需要时间O(n),总时间复杂度 O(n) 
    int BinaryResearch(int A[],int low,int high,int target)
    {
        int l = low;
        int h = high;
        while(l<=h)
        {
           int mid = (int)((h+l)/2);
           if(A[mid]==target) return mid;
           else if(A[mid]<target) l = mid+1;
           else h = mid-1;
        }
        return A[h]; 
    }
    int search1(int A[], int n, int target) {
       
         int index = 0;
         for(int i = 0;i<n-1;i++)
         {
           if(A[i]>A[i+1])
           {
             index = i;
             break;
           }
         }
         int a = BinaryResearch(A,0,index,target);
         int b = BinaryResearch(A,index+1,n-1,target);
         if(a==-1&&b==-1)
         return -1;
         else 
         return a==-1?b:a;
    }
    int search2(int A[], int n, int target) {
         //顺序查找 ,O(n)
         int index = -1;
         for(int i = 0;i<n;i++)
         {
         if(A[i]==target)
         {
            index = i;
         }}
         return index;
    }
    //完全的二分查找,O(logn) 
    int search3(int A[], int n, int target) {
         int left = 0;
         int right = n-1;
         while(left<=right)
         {
                int mid = (int)((left + right)/2);
                if(A[mid] == target) return mid;
                if(A[left]<A[mid])//A[mid]在前半部分
                {
                   if(target<A[mid]&&target>=A[left])
                   right = mid-1;
                   else left = mid+1; 
                } 
                else if(A[left]>A[mid])//A[mid]位于后半段 
                {
                   if(target>A[mid]&&target<=A[right])
                   left = mid+1;
                   else 
                   right = mid-1;
                }
                else left++; 
         }
         return -1;
         
    }


  • 相关阅读:
    Thinkphp5.0 模型hasOne、hasMany、belongsTo详解
    ES6中async和await说明和用法
    必会SQL练习题
    Git初识学习
    CI框架简单使用
    JavaScript 的 this 原理
    javascript实现游戏贪吃蛇
    js清除childNodes中的#text(选项卡中会用到获取第一级子元素)
    JavaNIO
    MongoDB入门_shell基本操作
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601440.html
Copyright © 2011-2022 走看看