zoukankan      html  css  js  c++  java
  • LeetCode(81) Search in Rotated Array II

    题目

    Follow up for “Search in Rotated Sorted Array”:
    What if duplicates are allowed?

    Would this affect the run-time complexity? How and why?

    Write a function to determine if a given target is in the array.

    分析

    这是一道类似于LeetCode 33 的题目,不同的就是这道题有可能出现数字重复,所以,我们不可能像上题那样找到旋转点,然后两次二分查找;

    我们可以根据序列特点,以二分查找思想为基础,对该算法进行一定程序的改进。

    AC代码

    class Solution {
    public:
        bool search(vector<int>& nums, int target) {
            if (nums.empty())
                return false;
    
            //求所给序列的长度
            int len = nums.size();
    
            int lhs = 0, rhs = len - 1;
            while (lhs <= rhs)
            {
                //右移一位减半,提升效能
                int mid = (lhs + rhs) >> 1;
                if (target == nums[mid])
                    return true;
    
                //若左侧、中间、右侧值相等 则左右同时内移一位
                if (nums[lhs] == nums[mid] && nums[mid] == nums[rhs])
                {
                    lhs++;
                    rhs--;
                }//if
                else if (nums[lhs] <= nums[mid])
                {
                    if (nums[lhs] <= target && target < nums[mid])
                    {
                        rhs = mid - 1;
                    }
                    else{
                        lhs = mid + 1;
                    }//else
                }//elif
                else{
                    if (nums[mid] < target && target <= nums[rhs])
                    {
                        lhs = mid + 1;
                    }//if
                    else{
                        rhs = mid - 1;
                    }//else
                }//else
            }//while
            return false;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    $.unique()去重问题
    js判断中文
    js URL中文传参乱码
    zabbix添加nginx监控
    TCP/IP与OSI参考模型原理
    100个linux系统常用指令
    read指令使用方法
    grep与正则表达式使用
    shell脚本中case的用法
    shell脚本:变量,文件判断,逻辑运算等纪要
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214841.html
Copyright © 2011-2022 走看看