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;
        }
    }
  • 相关阅读:
    IP报头结构
    C#组件项目设置与开发应用范例
    UDP数据报协议
    WOW 各等级属性换算表
    清理SQLSERVER日志
    正则表达式匹配EXCEL地址字符串
    TCP数据段格式
    MAC地址结构
    (转载) Delphi中打印条码的方法
    为了使用uart2, 发现6252中define了 SCCB_SERIAL_CLK_PIN 值为 22, 为了避免冲突, 手动修改其值为 23
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10063254.html
Copyright © 2011-2022 走看看