• LeetCode(33)Search in Rotated Sorted Array


    题目

    Suppose a sorted array 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.

    分析

    该题目是在一个旋转过的有序序列中查找关键字。
    显然的,不能用一次遍历顺序查找法,考察的关键是二分搜索算法。
    对于一个递增序列,在旋转点前后,也会保持递增排序不变。
    所以对该题目首先要找到整个序列中的最小元素,也就是旋转点,然后对两边子序列应用二分搜索,找到目标元素的下标。

    AC代码

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            if (nums.empty())
                return -1;
    
            //找到旋转点
            int pivot = findPivot(nums , 0 , nums.size()-1);
            int pos = binarySearch(nums, 0, pivot - 1, target);
            if (pos != -1)
                return pos;
            else
                pos = binarySearch(nums, pivot, nums.size() - 1, target);
    
            return pos != -1 ? pos : -1;
    
        }
    
        //寻找旋转点
        int findPivot(vector<int> &nums , const int &lhs , const int &rhs)
        {
    
            if (nums.empty() || lhs > rhs)
                return -1;
    
            int middle = (lhs + rhs) / 2;
    
            //如果中间元素大于左侧首位值lhs,则旋转点要么在lhs要么在middle+1 ~ rhs
            if (nums[middle] >= nums[lhs])
            {
                int pivot = findPivot(nums, middle + 1, rhs);
                if (pivot == -1)
                    return lhs;
                else if (nums[lhs] < nums[pivot])
                    return lhs;
                else
                    return pivot;
            }//反之,则旋转点要么在middle要么在lhs~middle-1
            else{
                int pivot = findPivot(nums, lhs, middle-1);
                if (pivot == -1)
                    return middle;
                else if (nums[middle] < nums[pivot])
                    return middle;
                else
                    return pivot;
            }//else 
        }
    
        int binarySearch(vector<int> &nums, const int &lhs , const int &rhs ,int target)
        {
            if (nums.empty() || lhs > rhs)
                return -1;
    
            int middle = (lhs + rhs) / 2;
            if (nums[middle] == target)
                return middle;
            else if (nums[middle] < target)
            {
                return binarySearch(nums, middle + 1, rhs, target);
            }
            else{
                return binarySearch(nums, lhs, middle - 1, target);
            }//else
        }
    };
    

    GitHub测试程序源码

  • 相关阅读:
    SpringBoot/SpringMVC Restful接口全局异常处理
    spring/springboot/springmvc启用GZIP压缩
    centos7启动SonarQube 8.6报错
    类型初始值设定项引发异常
    OCI is not properly installed on this machine (NOE1/INIT)
    动态调用webservice 此 XML 文档中禁用 DTD。
    系统缺少插件 系统插件已过期
    几种常见的函数
    MQTT 协议基本介绍
    etcd:从应用场景到实现原理的全方位解读【修订版】
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214897.html
Copyright © 2020-2023  润新知