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测试程序源码

  • 相关阅读:
    敏捷的调试
    敏捷的编码
    敏捷的需求分析
    敏捷的反馈
    敏捷的方法论
    敏捷的世界观
    MarkDown添加数学公式
    性能分析初学者指南
    可执行文件的装载与进程
    会话技术------客户端技术cookie
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214841.html
Copyright © 2011-2022 走看看