zoukankan      html  css  js  c++  java
  • [LeetCode]Search in Rotated Sorted 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.

    解题思路 :

    需要跳过重复的元素。

    class Solution {
    public:
        bool search(vector<int>& nums, int target) {
            size_t first = 0;
            size_t last = nums.size();
            
            while (first != last) {
                size_t mid = first + (last - first) / 2;
                if (nums[mid] == target) {
                    return true;
                } else if (nums[mid] > nums[first]) { // 递增
                    if (nums[first] <= target && target < nums[mid]) {
                        last = mid;
                    } else {
                        first = mid + 1;
                    }
                } else if (nums[mid] < nums[first]) {//递减
                    if (nums[mid] < target && target <= nums[last - 1]) {
                        first = mid + 1;
                    } else {
                        last = mid;
                    }
                } else {// 跳过重复元素
                    ++first;
                }
            }
            
            return false;
        }
    };
    

      

  • 相关阅读:
    Flask基础01
    Django logging配置
    JSONP和CORS跨域
    Scrapy框架
    请求库之urllib,requests及工具selenium
    MongoDB安装
    Django 视图层
    Django REST framework 2
    WebSocket
    爬虫性能相关
  • 原文地址:https://www.cnblogs.com/skycore/p/4849330.html
Copyright © 2011-2022 走看看