zoukankan      html  css  js  c++  java
  • 【Search in Rotated Sorted Array II 】cpp

    题目:

    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) {
                nums.erase(std::unique(nums.begin(), nums.end()),nums.end());
                int begin=0, end=nums.size()-1;
                while ( begin<=end )
                {
                    int mid = (begin+end)/2;
                    if ( nums[mid]==target ) return true;
                    // first half sorted
                    if ( nums[begin]<=nums[mid] )
                    {
                        if ( target>nums[mid] )
                        {
                            begin = mid+1;
                        }
                        else
                        {
                            if ( target>=nums[begin] )
                            {
                                end = mid-1;
                            }
                            else
                            {
                                begin = mid+1;
                            }
                        }
                        continue;
                    }
                    // second half sorted
                    if ( nums[mid]<nums[end] )
                    {
                        if ( target<nums[mid])
                        {
                            end = mid-1;
                        }
                        else
                        {
                            if ( target<=nums[end])
                            {
                                begin = mid+1;
                            }
                            else
                            {
                                end = mid-1;
                            }
                        }
                    }
    
                }
                return false;
        }
    };

    tips:

    通过这题熟悉了stl将vector去重的方法。

    采用了偷懒的做法:

    1. 先利用stl的unqiue把数组去重

    2. 再按照Search in Rotated Sorted Array这题的方法进行二分查找。

  • 相关阅读:
    Docker容器案例:应用 Mysql
    rpm 命令参数使用详解
    MySQL中的两种临时表
    Yum本地Rpm库设置
    编程学习 博客
    yum -------包安装库
    Linux 基础 —— RPM
    在CentOS上编译安装PostgreSQL
    Linux上安装JDK环境变量配置
    yum_rpm(利用dvd建立本地yum库)
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4574926.html
Copyright © 2011-2022 走看看