leetcode 33. Search in Rotated Sorted Array

LeetCode题解(Java实现)——33.Search in Rotated Sorted Array(循环有序数组) 前言 欢迎关注我的 Github 仓库 https://github.com/bigrotor187/awesome-java-notes ,如果觉得有帮助,请点个 star 哟,目前主要在更 leetcode题解(Java版)和 剑指offer题解(Java版),可以点个star。 文本已收录至我的GitHub仓库,欢迎Star:awesome-java-notes 33. Search in... 阅读详情

1.题目

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

从旋转数组中查找target.

2.思路 

肯定得用二分查找,不然超时。那么,怎么个二分法呢?首先,可以看一下旋转数组的几种状态(主要是nums[mid]所在的位置)


第一种情况,如果target == nums[mid] ,最理想不过了,直接返回。

第二种情况,如果target < nums[mid],那么target所在的区间如下图:


第三种情况 原理同上。。。

代码如下:

class Solution {
public:
int search(vector<int>& nums, int target) {
    int len = nums.size();
    int left = 0,right = len-1;
    int mid;
    while(left <= right)
    {
        mid = left + (right - left)/2;
        if(nums[mid] == target)
            return mid;
        else if(nums[mid] > target)
        {
            if(nums[left] > nums[right]) // 如果在一个有旋转的序列里
            {
                if( (nums[mid] < nums[left]) || (target >= nums[left]) ) // >=号特别重要
                    right = mid - 1;
                else
                    left = mid + 1;
            }
            else // 在一个正常序列里
                right = mid - 1;
        }
        else
        {
            if(nums[left] > nums[right])
            {
                if( (nums[mid] < nums[left]) && (target >= nums[left]) )
                    right = mid - 1;
                else
                    left = mid + 1;
            }
            else
                left = mid + 1;
            
        }
    }
    return -1;
}
};


旗鱼优化算法(SFO)详解:从海洋猎手到智能优化 旗鱼优化算法(SFO)是一种新型群体智能优化算法,灵感来源于旗鱼的群体捕食行为。该算法采用双种群机制,模拟旗鱼(精英个体)与沙丁鱼(普通个体)的交互过程,通过交替攻击策略实现探索与开发的平衡。核心机制包括:基于猎物密度的旗鱼位置更新、随迭代衰减的攻击力度控制、以及捕食替换机制。SFO具有参数少、全局搜索能力强等特点,在高维复杂优化问题中表现优异。算法通过模拟自然界中的群体智能行为,为解决工程优化问题提供了新思路。 阅读详情

相关推荐

UG/NX二次开发Siemens官方NXOPEN实例解析—1.3 BlockStyler/ExtrudewithPreview

随着工业智能化的不断发展,UG二次开发的需求越来越多,也吸引了大批的二开从业人员,本人作为一名资深IT从业者(10年+)也毅然加入二次开发大军。然而,和流行IT行业(互联网、金融、医疗等)相比,工业智能化的门槛显得更高一点,专业的工业软件,相对封闭的开发理念和更小的开发圈子,让刚进入二开的从业者有点举步维艰。边学边整理,希望通过这系列文章的整理能给二开的生态增添一叶绿。

MarcoPro的博客 1633

leetcode-33. Search in Rotated Sorted Array

leetcode-33. Search in Rotated Sorted Array题目: 这里基本思想就是二分法,而二分法其实并不需要严格排序,比如这一题,由于是Rotated,所以如果将数组二分的话至少会有一半是严格二分的,又因为不存在重复元素,我们只要判断严格递增区域的是否包含target就好了。如果严格递增区域没有则必定在另一半。 当然corner case还是有点麻烦的。。需要认真判断一下。这里

千念飞羽的专栏 402

基于Apache MINA SSHD配置及应用

Apache MINA SSHD是一个基于Java的开源SSH服务器/客户端实现,支持SSH2协议,提供文件传输、shell访问等功能。该代码实现了一个SftpClientService服务类,封装了SFTP文件操作,包括读取文件(readOnce/readLines)和写入文件(writeOnce)等核心功能。通过SftpProperties配置类管理连接参数,并采用Builder模式创建SSH会话。主要特点包括:支持大文件分块传输、自动创建目录、严格的异常处理和...

流沙QuickSand 945

LeetCode 33. Search in Rotated Sorted Array

题目描述(中等难度) 开始的时候想复杂了,其实就是一个排序好的数组,把前边的若干的个数,一起移动到末尾就行了。然后在 log (n) 下找到给定数字的下标。 总的来说,log(n),我们肯定得用二分的方法了。 解法一 参考这里-Binary-search-solution)首先我们想一下变化前,正常的升序。我们怎么找给定的数字。 我们每次只关心中间位置的值(这一点很重要),也就是上图 3 位置...

wind_liang的博客 1072

计算机组成原理(第三版)唐朔飞-第五章输入输出系统-课后习题

计算机组成原理(第三版)唐朔飞-第五章输入输出系统-课后习题

weixin_45735391的博客 6万+

Windows 11 安装 Miniconda + Mamba,配置国内源

本文详细介绍了在 Windows 11 系统下安装 Miniconda 并配置 Mamba 的完整流程,包括选择精简版 Miniconda 的理由、安装过程中的关键选项设置、配置清华大学镜像源以加速包下载,以及在 base 环境中设置 pip 国内源。同时说明了 Mamba 相较 Conda 的性能优势,并指导用户完成 Mamba 安装与 Shell 集成,最终通过命令验证环境管理功能,帮助用户构建高效、轻量的 Python 开发环境。

寒水馨 · 轻量级技术文档 · hanshuixin.org 3345

leetcode 33 Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found ...

GoRunningSnail的博客 247

CUDA:实现使用cuSolverSP底层API实现Cholesky因式分解(附完整源码)

CUDA:实现使用cuSolverSP底层API实现Cholesky因式分解(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 343

LeetCode 33 Search in Rotated Sorted Array 题解

LeetCode 33 Search in Rotated Sorted Array题意思路代码总结 题意 给出一个数组,该数组是由一个升序排列的数组以某个轴旋转后得到的。例如4 5 6 7 0 1 2是由0 1 2 4 5 6 7旋转(我认为是交换)后得到的。给你一个目标值target,要求判断数组中是否存在这个值,存在的话给出它的位置,否则返回-1。 注: 数组中无重复数组,要求算法时间复杂度...

EricJeffrey的博客 237

高频网络协议与编程IO相关面试基本问题和知识点整理

网络IO相关基本高频面试基本问题和知识点整合

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 173万+

【27】软考软件设计师——数据流图(DFD)补全题满分精讲|下午15分大题深度拆解

本文是《软件设计师·50讲通关|从零基础到工程师职称》专栏第27篇,深度精讲**下午案例题第1道必考大题:数据流图(DFD)补全**,该题单题分值高达**12 ~ 15分**,是整张试卷最稳的保底得分大题。我结合多年备考复盘与真题阅卷规则,超详细拆解DFD四大核心元素标准定义、机考绘图规范、三层分层逻辑、**父图子图平衡刚性扣分规则**,升级强化版「DFD满分补全三步法」;复刻历年高频真题完整流程,拆解缺失数据流定位、实体/存储辨析、平衡改错、文字需求对照全流程,配套**阅卷满分答题话术、机考避坑细则

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 590

[Leetcode] 33. Search in Rotated Sorted Array 解题报告

题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the ar

魔豆(Magicbean)的博客 1062

腾讯面试——机器学习岗面试总结

先写合并两个有序数组,接着写合并n个有序的数组,假设总共m个数,讲了一个思路两两合并直到只剩下一个数组,分析一下时间复杂度(MlogN),面试官不满意,然后想了一下说了另一个思路,用n个指针开始指向各个数组的首端,用一个优先队列维护他们的最小值,每次拿出最小值的指针然后插入该指针的下一个值。感觉跟二面面试官聊得还是挺开心的,他详细地介绍了他们部门所做的业务,然后问了一下什么时候能来实现,我说只能暑假七八两个月,他觉得有点晚,这样子不利于转正,有些人都实习半年的,回去讨论一下,正式批之前给我答复。

FPGA/MATLAB学习教程/源码/项目合作开发 1231

LeetCode33——Search in Rotated Sorted Array

LeetCode33——Search in Rotated Sorted Array 简单来说就是在数组中查找  输入的  target,如果找到返回索引,如果没有找到返回-1 在中STL提供find方法,虽然事先知道是O(n)复杂度的顺序查找,还是首先就试了试,结果是可以通过的 注:返回的是迭代类型。 代码: class Solution { public: int

上善若水 513

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Leetcode 33 Search in Rotated Sorted Array

思路一: 看到时间复杂度logn,就知道要用binary search。那么第一种方法是two pass binary search。先用一次binary search把rotate point找出来,然后再判断target在rotate pointer前还是后。判断好了就再进行一次binary search。得到答案。附上代码: class Solution { int [] nums; int target; public int find_rotate_index(int left, .

GoodJobJasper的博客 189

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Leetcode33. Search in Rotated Sorted Array

那说明target就在这里面,否则只能在右半边。我们可以考虑只在有序的部分里寻找。旋转数组搜索,其中元素唯一。类似之前旋转数组找最小。,这说明左边是有序的。

思维缜密的博客 570

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

【LeetCode】 33. Search in Rotated Sorted Array 搜索旋转排序数组(Medium)(JAVA)

【LeetCode】 33. Search in Rotated Sorted Array 搜索旋转排序数组(Medium)(JAVA) 题目地址: https://leetcode.com/problems/search-in-rotated-sorted-array/ 题目描述: Suppose an array sorted in ascending order is rotated at...

qq_16927853的博客 197

[leetcode] 33. Search in Rotated Sorted Array 解题报告

题目链接:https://leetcode.com/problems/search-in-rotated-sorted-array/ Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2)

小榕流光的专栏 2034

leetcode33_Search in Rotated Sorted Array

一.问题描述 Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the

越努力越幸运 332

leetcode No33. Search in Rotated Sorted Array

Question: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in th

Dufre 855

LeetCode 33. Search in Rotated Sorted Array(二分查找)

题目来源:https://leetcode.com/problems/search-in-rotated-sorted-array/ 问题描述 33.Search in Rotated Sorted Array Medium Suppose an array sorted in ascending order is rotated at some pivot unknown to you...

da_kao_la的博客 404

【LeetCode 33】 Search in Rotated Sorted Array

题目描述 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. Y

iCode_girl的博客 200

【LEETCODE】33-Search in Rotated Sorted Array [Python]

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its

aliceyangxi1987的博客 3264

leetcode-33 Search in Rotated Sorted Array

问题描述: Supposea sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the arrayretu

woliuyunyicai的专栏 946

Leetcode C++ 33. Search in Rotated Sorted Array

Leetcode 33. Search in Rotated Sorted Array 原文: Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You...

sinat_35177634的博客 310

【Java】【LeetCode】33. Search in Rotated Sorted Array

题目: Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,[0,1,2,4,5,6,7]might become[4,5,6,7,0,1,2]). You are given a target value to search. If f...

zhelong19830726的博客 228
上一篇: leetcode 32. Longest Valid Parentheses
下一篇: leetcode 34. Search for a Range
csdn_lisword
博客等级 码龄11年 0粉丝 50原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值