zoukankan      html  css  js  c++  java
  • leetcode68-search-in-rotated-sorted-array-ii

    题目描述

    继续思考题目 "Search in Rotated Sorted Array":

    如果数组种允许有重复元素怎么办?
    会影响时间复杂度吗?是怎样影响时间复杂度的,为什么?
    编写一个函数判断给定目标值是否在数组中。

    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.


    示例1

    输入

    复制
    [1],1

    输出

    复制
    true
    class Solution {
    public:
        /**
         *
         * @param A int整型一维数组
         * @param n int A数组长度
         * @param target int整型
         * @return bool布尔型
         */
        bool search(int* A, int n, int target) {
            // write code here
            for (int i=0;i<n;i++){
                if (A[i]==target)
                    return true;
            }
            return false;
        }
    };


    class Solution {
    public:
        /**
         *
         * @param A int整型一维数组
         * @param n int A数组长度
         * @param target int整型
         * @return bool布尔型
         */
        bool search(int* A, int n, int target) {
            // write code here
            int first=0;
            int last=n-1;
            while (first<=last){
                int mid=first+(last-first)/2;
                if (A[mid]==target)
                    return true;
                if (A[first]==A[mid]&&A[mid]==A[last]){
                    first++;
                    last--;
                    
                }
                else if (A[first]<=A[mid])
                {
                    if (A[first]<=target && target<A[mid])
                        last=mid-1;
                    else
                        first=mid+1;
                    
                }
                else if (A[mid]<=A[last]){
                    if (A[mid]<target && target <=A[last])
                        first=mid+1;
                    else
                        last=mid-1;
                }
            }
            return false;
        }
    };

  • 相关阅读:
    POJ 3680_Intervals
    POJ 3680_Intervals
    POJ 3686_The Windy's
    POJ 3686_The Windy's
    Codeforces 629C Famil Door and Brackets
    Codeforces 629D Babaei and Birthday Cake(树状数组优化dp)
    Codeforces 629D Babaei and Birthday Cake(线段树优化dp)
    Codeforces 628F Bear and Fair Set
    18.04.26 魔兽世界终极版
    18.4.20 STL专项练习8选6
  • 原文地址:https://www.cnblogs.com/hrnn/p/13413334.html
Copyright © 2011-2022 走看看