剑指 Offer(第2版)面试题 53:在排序数组中查找数字

《剑指offer》Java版 一、引言 《剑指offer》可谓是程序猿面试的神书了,在面试中帮了我很多,大部分面试的算法题都会遇到原题或者是类似的题。但是书上的代码都是C版的,我在这里整理了一份Java版的代码供大家学习参考,这些代码我都是在OJ上跑过全AC的,所以正确性你大可放心。 二、目录 1赋值运算函数 2单例设计模式 3二维数组中查找目标值 4替换字符串中的空格 5从尾到头打印链表 6由前序和中序遍历重建二叉树 7用两... 阅读详情

剑指 Offer(第2版)面试题 53:在排序数组中查找数字

题目一:数字在排序数组中出现的次数

题目来源:67. 数字在排序数组中出现的次数

题目描述:统计一个数字在排序数组中出现的次数。

思路 1:顺序遍历,统计出现次数

代码:

class Solution {
public:
    int getNumberOfK(vector<int>& nums , int k) {
        int count = 0;
        for(int &num:nums)
            if(num == k)
                count++;
        return count;
    }
};

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

思路 2:二分查找

代码:

class Solution {
public:
    int getNumberOfK(vector<int>& nums , int k) {
        return upper_bound(nums.begin(), nums.end(), k) - lower_bound(nums.begin(), nums.end(), k);
    }
};

自己实现 upper_bound 和 lower_bound:

class Solution
{
public:
	int getNumberOfK(vector<int> &nums, int k)
	{
		if (nums.empty())
			return 0;
		int firstIdx = getFirstTargetIndex(nums, k), lastIdx = getLastTargetIndex(nums, k);
		if (firstIdx != -1 && lastIdx != -1)
			return lastIdx - firstIdx + 1;
		return 0;
	}
	// 辅函数 - 得到数组 nums 中第一个 target 的下标
	int getFirstTargetIndex(vector<int> &nums, int target)
	{
		if (nums.empty())
			return -1;
		int left = 0, right = nums.size() - 1;
		while (left <= right)
		{
			int mid = (left + right) / 2;
			if (nums[mid] == target)
			{
				if ((mid > 0 && nums[mid - 1] != target) || mid == 0)
					return mid;
				else
					right = mid - 1;
			}
			else if (nums[mid] > target)
				right = mid - 1;
			else
				left = mid + 1;
		}
		return -1;
	}
	// 辅函数 - 得到数组 nums 中最后一个 target 的下标
	int getLastTargetIndex(vector<int> &nums, int target)
	{
		if (nums.empty())
			return -1;
		int left = 0, right = nums.size() - 1;
		while (left <= right)
		{
			int mid = (left + right) / 2;
			if (nums[mid] == target)
			{
				if ((mid < nums.size() - 1 && nums[mid + 1] != target) || mid == nums.size() - 1)
					return mid;
				else
					left = mid + 1;
			}
			else if (nums[mid] > target)
				right = mid - 1;
			else
				left = mid + 1;
		}
		return -1;
	}
};

书上的 upper_bound 和 lower_bound 是递归实现的,也可以。

复杂度分析:

时间复杂度:O(logn),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

题目二:0 到 n-1 中缺失的数字

题目链接:68. 0 到 n-1 中缺失的数字

题目描述:一个长度为 n−1 的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围 0 到 n−1 之内。在范围 0 到 n−1 的 n 个数字中有且只有一个数字不在该数组中,请找出这个数字。

思路1:求和

0 到 n−1 的所有数字之和为 n(n-1)/2,数组 nums 的和为 accumulate(nums.begin(), nums.end(), 0),两者之差就是缺失的数字。

代码:

class Solution
{
public:
	int getMissingNumber(vector<int> &nums)
	{
		int n = nums.size();
		return n * (n + 1) / 2 - accumulate(nums.begin(), nums.end(), 0);
	}
};

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

思路2:异或

异或的性质:

  • a ^ a = 0
  • 0 ^ a = a
  • a ^ a ^ b = b

我们可以将数组下标异或数组元素,最后再异或数组长度即可得到缺失的数字。

如果没缺数字,异或的最终值即数组的长度。

代码:

class Solution
{
public:
	int getMissingNumber(vector<int> &nums)
	{
		if (nums.empty())
			return 0;
		int ans = 0;
		for (int i = 0; i < nums.size(); i++)
			ans ^= (i ^ nums[i]);
		return ans ^ nums.size();
	}
};

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

思路3:二分查找

这道题目给定的是递增数组,假设数组中第一个缺失的数是 x,那么数组中的数如下所示:

请添加图片描述

缺失的数 x 之前的数是与数组下标一一对应的,而之后的数(包括 x 自己)不与下标一一对应。即数组左边蓝色部分都满足 nums[i] == i,数组右边橙色部分都不满足 nums[i] == i,因此我们可以二分出分界点 x 的值。

特殊情况:当所有数都满足 nums[i] == i 时,表示缺失的是 n。

代码:

class Solution
{
public:
	int getMissingNumber(vector<int> &nums)
	{
		if (nums.empty())
			return 0;
        int n = nums.size();
        int left = 0, right = n - 1;
        while (left < right)
        {
            int mid = (left + right) / 2;
            if(nums[mid] != mid)
                right = mid;
            else
                left = mid + 1;
        }
        return nums[left] == left ? n : left;
	}
};

复杂度分析:

时间复杂度:O(logn),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

题目三:数组中数值和下标相等的元素

题目链接:69. 数组中数值和下标相等的元素

题目描述:假设一个单调递增的数组里的每个元素都是整数并且是唯一的。请编程实现一个函数找出数组中任意一个数值等于其下标的元素。

思路1:遍历

代码:

class Solution {
public:
    int getNumberSameAsIndex(vector<int>& nums) {
        if (nums.empty())
            return -1;
        for (int i = 0; i< nums.size(); i++)
            if (nums[i] == i)
                return i;
        return -1;
    }
};

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

思路2:二分查找

代码:

class Solution {
public:
    int getNumberSameAsIndex(vector<int>& nums) {
        if (nums.empty())
            return -1;
        int n = nums.size();
        int left = 0, right = n - 1;
        while (left <= right)
        {
            int mid = (left + right) / 2;
            if (nums[mid] == mid)
                return mid;
            else if (nums[mid] > mid)
                right = mid - 1;
            else
                left = mid + 1;
        }
        return -1;
    }
};

复杂度分析:

时间复杂度:O(logn),其中 n 是数组 nums 的长度。

空间复杂度:O(1)。

牛客网剑指Offer - java版 剑指Offer - java版 文章目录剑指Offer - java版JZ01JZ02 替换空格JZ03 从尾到头打印链表JZ04 重建二叉树JZ05 用两个栈实现队列JZ06 旋转数组的最小数字JZ07 斐波那契数列JZ08 跳台阶问题JZ09 青蛙跳台阶JZ10 矩形覆盖JZ11 二进制中1的个数JZ12 数值的整数次方JZ13 调整数组顺序,使奇数位于偶数前面JZ14 链表中倒数第k个结点JZ15 反转链表JZ16 合并两个排序的链表JZ17 树的子结构JZ18 二叉树的镜像JZ19 顺时针打印矩阵J 阅读详情

相关推荐

告别TwinCAT:手把手教你用IgH EtherCAT Master在LinuxCNC上搭建实时运动控制平台

本文详细介绍了如何利用IgH EtherCAT Master和LinuxCNC搭建开源实时运动控制平台,替代商业软件TwinCAT。通过分步指南,包括实时Linux环境配置、EtherCAT主站安装、LinuxCNC集成及多轴同步控制实现,帮助开发者构建高性能、低成本的工业自动化解决方案。

weixin_42641741的博客 406

剑指 Offer 53 - II: 0~n-1中缺失的数字

看到这道题的第一反应就是二分查找,由于是递增的所以二分查找所需的时间很短 ,设置一个左,一个右,一个中间,如果判断吧不同需要想下前面是否一样,如果是那么就找到,不是再继续二分查找。没有最后一个多余的判断的话,会永远返回0,因为程序是有可能跳出循环的,就是在当前长度找不到的时候,所以直接返回length即可(只有这一种可能找不到从而跳出循环)谨记,一定是和nums的长度比较,因为找不到的话,那么就说明最后L和R会收敛至相等的程度,然后L+1(越界,等于length),所以才需要和length去比较!

MengyuyangEddy的博客 251

掌控板玩板指南1:初识掌控板、扩展板、Mind+编辑器

掌控板、I/O扩展板入门

好乐无荒之地 1万+

剑指 Offer 53 - I. 在排序数组中查找数字 I

还是要注意细节,边界问题很容易出错。

JehanRio's Private Blog 110

汽车工程师必看:从CAN到Ethernet,6种车载通信协议全解析(附应用场景对比)

本文全面解析了从CAN到Ethernet的6种车载通信协议,包括CAN、LIN、MOST、FlexRay等,并对比了它们的应用场景和技术特点。文章详细介绍了各协议的演进历程、技术优势及在现代汽车中的混合网络架构设计,为汽车工程师提供了实用的协议选型指南和未来通信技术发展趋势。

weixin_28683689的博客 502

手把手教你用CubeMX给GD32F103点灯、调串口(附完整工程)

本文详细介绍了如何使用CubeMX为GD32F103开发板配置GPIO点灯和串口通信,包含完整的工程创建、代码构建和测试流程。特别强调了GD32与STM32的差异点及常见避坑技巧,帮助开发者快速上手GD32开发。

weixin_42566424的博客 317

剑指Offer 第53题:数字在升序数组中出现的次数

简单来说,我们就是先折半聚拢,然后分开扩散查找的思想,当然这得建立在数组有序的情况下,因此我使用了快排,但事实是不用快排也能运行,可以猜出牛客网中的例子应该都是有序的,总的来说知识点不多,无非就是分支与循环、函数、数组,然后再利用折半+遍历,就能解决这个问题,简单标签当之无愧。

北 海的博客 1439

芒果YOLOv7改进48:主干篇:独家首发改进:目标检测新范式骨干PPHGNetv2改进版,充分融合信息特征,提升YOLOv7检测能力

YOLOv7代码改进实践 | 独家首发改进 PPHGNetv2 改进版结构

包括YOLOv5、YOLOv7、YOLOv8等模型改进 1858

《暑假每日一题》Week 1: 6.20 - 6.26

混合背包问题

sdhahk的博客 1008

CloudCompare 二次开发(36)——非均匀体素降采样

使用CloudCompare与PCL编程实现的非均匀体素降采样。

点云侠的博客 750

1.DJI-payload SDK负载开发准备和硬件连接及运行示例代码

大疆psdk开发环境

哒宰的博客 1444

剑指offer53~在排序数组中查找数字

The Amount Of A Certain Character In Sorted Array Description 统计一个数字在排序数组中出现的次数。例如,输入排序数组{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4. Solution 方法一:暴力搜索 在O(n)的时间内便利,统计这个数字出现的次数。 方法二:二分法定位数字出现的位置,按照...

Daci Studio 225

结构化数据特征构建神器openfe的实战代码

最近订阅专栏的几位同学一起参加了AI比赛,该比赛的数据形式是结构化的。随着特征和模型的不断迭代优化,达到了一个难以跨越的瓶颈。希望我能够给出一些有效的方法,帮助他们提高成绩。在个人的调研和体验后,向他们推荐了结构化数据特征构建神器openfe,最终也帮助他们提升了十来名的成绩,个人也感到十分的欣慰。特意写此博客,希望能够帮助更多的同学。 文章目录 1. 安装 2. 实战例子一 3. 实战例子二

herosunly的博客 3万+

大神整理的剑指Offer【所有面试题汇总】

    剑指Offer学习   剑指Offer这本书已经学习完了,从中也学习到了不少的东西,现在做一个总的目录,供自已和大家一起参考,学如逆水行舟,不进则退。只有不断地学习才能跟上时候,跟得上技术的潮流! 所有代码下载【https://github.com/Wang-Jun-Chao/coding-interviews】 目录 第01-10题 【剑指Offer学习】【面试题02:...

晓飛的博客 3万+

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

深度学习工具包 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")

剑指offer面试题53(java版):数字在排序数组中出现的次数

welcome to my blog 剑指offer面试题53(java版):数字在排序数组中出现的次数 题目描述 统计一个数字在排序数组中出现的次数 思路 找到第一个k的索引和最后一个k的索引就知道有序数组中k出现的次数了 笔记 二分法中,最好先判断arr[mid]>k, 接着arr[mid]<k, 剩下的便是arr[mid]==k, arr[mid]==k这个条件就不用显式地...

littlehaes的博客 649

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

《剑指Offer》解题目录(更新完毕)

题目来源于LeetCode上的《剑指Offer》,这里做一个目录方便大家查找。另外有本人的LeetCode解题目录、《程序员面试金典》可点击链接查看。

Michael是个半路程序员 6165

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

剑指Offer LeetCode 面试题53 - I. 在排序数组中查找数字 I

剑指Offer LeetCode 面试题53 - I. 在排序数组中查找数字 I

TrueDei 1411

【剑指Offer学习】【所有面试题汇总】

剑指Offer学习  剑指Offer这本书已经学习完了,从中也学习到了不少的东西,现在做一个总的目录,供自已和大家一起参考,学如逆水行舟,不进则退。只有不断地学习才能跟上时候,跟得上技术的潮流!目录第01-10题【剑指Offer学习】【面试题02:实现Singleton 模式——七种实现方式】【剑指Offer学习】【面试题03:二维数组中的查找】【剑指Offer学习】【面试题04:替换空格】【剑指O

https://github.com/Wang-Jun-Chao 5万+

剑指Offer对答如流系列 - 在排序数组中查找数字

文章目录面试题53:在排序数组中查找数字一、题目描述二、问题分析三、问题解答 面试题53:在排序数组中查找数字 一、题目描述 问题(1) 数字在排序数组中出现的次数 统计一个数字在排序数组中出现的次数。 例如输入排序数组{1, 2, 3, 3,3, 3, 4, 5}和数字3,由于3在这个数组中出现了4次,因此输出4。 问题(2)0到n-1中缺失的数字 一个长度为n-1的递增排序数组中的所有数字都是...

明月沉江春雾晓 2171

【剑指Offer】面试题:数组

剑指Offer中一共有12道关于数组的面试题 目录 面试题3:数组中重复的数字 面试题4:二维数组中的查找 面试题11:旋转数组的最小数字 面试题21:调整数组顺序使奇数位于偶数前面 面试题39:数组中出现次数超过一半的数字 面试题42:连续子数组的最大和 面试题45:把数组排成最小的数 面试题51:数组中的逆序对 面试题53:在排序数组中查找数字 面试题56:数组中数字出...

Dora_5537的博客 636

剑指offer第二版(Python3)--面试题53 :在排序数组中查找数字

统计一个数字在排序数组中出现的次数。

鲁班七号 619

Leetcode刷题:剑指offer【面试题53 在排序数组中查找数字】

【面试题53-I 在排序数组中查找数字】 面试题53 在排序数组中查找数字 I:统计一个数字在排序数组中出现的次数。 思路:由于是已排序数组,可以用二分查找找到我们的目标元素,但找到的位置不一定,可能前后都有相同的数字。然后再用双指针 i 和 j 分别指向找到的元素位置两侧,判断是否等于 target,若相等则计数器加 1,并移动指针。 class Solution: def search(self, nums: List[int], target: int) -> int:

学习 & 分享 ~ 381

《剑指offer》面试题53:在排序数组中查找数字

题目:数字在排序数组中出现的次数 统计一个数字在排序数组中出现的次数。例如,输入{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4。 思路:改进运用二分查找 接下来我们思考如何更好地利用二分查找算法。假设我们是统计数字k在排序数组中出现的次数。在前面的算法中时间主要消耗在如何确定重复出现的数字的第一个k和最后一个k的位置上,有没有可能用二分查找算法直接找到第一个...

qq_43502142的博客 258

剑指offer | 面试题53 - I.数字在排序数组中出现的次数

转载本文章请标明作者和出处 本文出自《Darwin的程序空间》 本文题目和部分解题思路来源自《剑指offer》第二版 开始行动,你已经成功一半了,献给正在奋斗的我们 题目 统计一个数字在排序数组中出现的次数 示例: 输入: nums = [5,7,7,8,8,10], target = 8 输出: 2 解题分析 首先我们分析一下题干,一个排序的数组,我们应该下意识的相到,排序的数组,百分之9...

程序员大航子 8060

剑指Offer——面试题53:在排序数组中查找数字

题目一:数字在排序数组中出现的次数 题目:统计一个数字在排序数组中出现的次数。例如输入排序数组{1, 2, 3, 3, 3, 3, 4, 5}和数字3,由于3在这个数组中出现了4次,因此输出4。 #include<iostream> #include<algorithm> #include<set> #include<vector> #include...

愿你慢慢变强的博客 281

剑指Offer - 面试题53 - I. 在排序数组中查找数字 I(二分查找的变形版本)

1. 题目 统计一个数字在排序数组中出现的次数。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: 2 示例 2: 输入: nums = [5,7,7,8,8,10], target = 6 输出: 0 限制: 0 <= 数组长度 <= 50000 类似题目:LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置(二分...

Michael是个半路程序员 2769
上一篇: Leetcode2928. 给小朋友们分糖果 I
下一篇: 剑指 Offer(第2版)面试题 54:二叉搜索树的第 k 大节点
UestcXiye
博客等级 码龄8年 9047粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址