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

  • 相关阅读:
    Pages.Instance is null when installing in subdirectory(ScrewTurn Wiki)
    20082009年中国嵌入式开发从业人员调查报告
    同济大学软件学院院长谈嵌入式方向选择
    WCF vs .NET Remoting 2.0
    RCP全局缓存
    对hibernate的set集合进行排序
    汇编基础——常用寄存器及其用途
    如何做外链
    linux学习之linux百问2,不断更新
    Hibernate中createQuery与createSQLQuery两者的区别
  • 原文地址:https://www.cnblogs.com/hrnn/p/13413334.html
Copyright © 2020-2023  润新知