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.

    Your algorithm's runtime complexity must be in the order of O(log n).

    Example 1:

    Input: nums = [4,5,6,7,0,1,2], target = 0
    Output: 4
    

    Example 2:

    Input: nums = [4,5,6,7,0,1,2], target = 3
    Output: -1

    用binary search,循环终止条件是 l + 1 >= r(这样的话最后需要判断一下l 和 r 位置元素是否等于target)

    由于数组旋转过,由两部分递增的序列组成。首先判断l 和 m 所在元素的大小关系,如果[l, m]是递增序列,进一步判断target是否在该范围中,并用binary search查找target;如果nums[l] > nums[m],说明[l, m)不是递增序列,而[m, r]是递增序列,进一步判断target是否在该范围中,并用binary search查找target。

    时间:O(logN),空间:O(1)

    class Solution {
        public int search(int[] nums, int target) {
            if(nums == null || nums.length == 0) return -1;
            int l = 0, r = nums.length - 1;
            
            while(l + 1 < r) {
                int m = l + (r - l) / 2;
                if(nums[m] == target)
                    return m;
                if(nums[l] < nums[m]) {
                    if(nums[l] <= target && target <= nums[m])
                        r = m;
                    else
                        l = m;
                }
                else {
                    if(nums[m] <= target && target <= nums[r])
                        l = m;
                    else
                        r = m;
                }
            }
            if(nums[l] == target) return l;
            if(nums[r] == target) return r;
            return -1;
        }
    }
  • 相关阅读:
    linux上的常用的进程与内存优化命令
    ubuntu 上运行的django 出现No space left on device错误
    openstack 使用pbr配置,setup.cfg的格式与含义
    openstack中安装包与组件
    对drf序列化器的理解
    对商品数据表的理解
    首页广告数据表的理解
    对省市区地址的理解
    对邮箱验证的理解
    用户中心个人信息实现的理解
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10063254.html
Copyright © 2011-2022 走看看