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     }
  • 相关阅读:
    yaml 文件解析
    python 实现自动部署测试环境
    运行ride.py报错,闪退
    selenium 配置ie11 浏览器
    自动化测试(1)selenium+python+chrome 连接测试
    scrapy爬虫框架
    drf内置排序源码
    celery基本使用
    C# 如何复制(拷贝)Label控件上的文本【新方法】
    C# 使用PictureBox实现图片按钮控件
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7675385.html
Copyright © 2011-2022 走看看