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


    比较笨的办法, 既然数组被旋转了,找出在哪里旋转的就好.接着就是普通的二分查找,使用stl自带的binary_search也可以.
    但是本题有一个test case是 [1,3] 3 ???? 这压根没有旋转啊. 所以需要额外一个判断.
    class Solution {
    public:
        int findMax(vector<int> &nums)
        {
            int l=0,r=nums.size()-1,m;
            while(l<=r)
            {
                m=(l+r)/2;
                if(nums[l]<nums[m]) l=m;
                else if(nums[l]==nums[m]) break;
                else r=m-1;
            }
    
            return nums[r]>=nums[l]? r:l;
        }
        
        int bs(vector<int> &nums, int l, int r, int t)
        {
            int m;
            while(l<=r)
            {
                m=(l+r)/2;
                if(nums[m]<t)
                    l=m+1;
                else if(t<nums[m])
                    r=m-1;
                else
                    return m;
            }
            return -1;
        }
        int search(vector<int>& nums, int target) {
            if(nums.empty())return -1;
            if(1==nums.size())return nums[0]==target?0:-1;
            int n=nums.back()>=nums[0]? nums.size()-1:findMax(nums);if(target>=nums[0])
                return bs(nums,0,n,target);
            else
                return bs(nums,n+1,nums.size()-1,target);
        }
    
    };
  • 相关阅读:
    ABAP常用函数归纳
    abap 优化之ST05
    对统驭科目和特别总账标志的理解
    会计凭证修改函数的使用
    会计凭证替代 OBBH
    屏幕切换
    se37 函数中的异常使用
    清帐函数的使用
    使用Servlet和JSp在浏览器上实现对数据库表的增删改查(新手)
    Java中的Xml配置文件(新手)
  • 原文地址:https://www.cnblogs.com/lychnis/p/11787595.html
Copyright © 2011-2022 走看看