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;
    }
};

posted on 2020-08-01 09:55  滚雪球效应  阅读(99)  评论(0编辑  收藏  举报