zoukankan      html  css  js  c++  java
  • 33. Search in Rotated Sorted Array

    Suppose an array sorted in ascending order 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.

    假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。

     1     public int search(int[] nums, int target) {
     2         int n = nums.length;
     3         int lo=0,hi=n-1;
     4         // find the index of the smallest value using binary search.
     5         // Loop will terminate since mid < hi, and lo or hi will shrink by at least 1.
     6         // Proof by contradiction that mid < hi: if mid==hi, then lo==hi and loop would have been terminated.
     7         while(lo<hi){
     8             int mid=(lo+hi)/2;
     9             if(nums[mid]>nums[hi]) lo=mid+1;
    10             else hi=mid;
    11         }
    12         // lo==hi is the index of the smallest value and also the number of places rotated.
    13         int rot=lo;
    14         lo=0;hi=n-1;
    15         // The usual binary search and accounting for rotation.
    16         while(lo<=hi){
    17             int mid=(lo+hi)/2;
    18             int realmid=(mid+rot)%n;
    19             if(nums[realmid]==target)return realmid;
    20             if(nums[realmid]<target)lo=mid+1;
    21             else hi=mid-1;
    22         }
    23         return -1;
    24     }
  • 相关阅读:
    零散的学习总结
    JSON学习整理
    轮播图
    关于new Object的小结
    js函数声明和函数表达式的区别
    float小结
    DOM文档加载步骤
    css主要的浏览器兼容性问题
    js for循环小记
    CANVAS中的lineWidth小计
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7675385.html
Copyright © 2011-2022 走看看