leetCode Single Number I II III

每天一道LeetCode-----一个整数序列,每个元素出现两次,只有一个(两个)出现一次,找到这个(这两个)元素 Single Number 原题链接Single Number 一个整数序列,每个数字都出现两次只有一次数字出现了一次,找到只出现一次的那个数字 位运算的异或算法有如下几个性质 值相同的两个数字异或结果为0,即a ^ a = 0 交换律,即a ^ b = b ^ a 综上两条性质,得到a ^ b ^ b = b ^ a ^ b = b ^ b ^ a = a 所以只需要遍历一遍序 阅读详情

Single Number系列

Single Number I

Given an array of integers, every element appears twice except for one. Find that single one.

题目描述:

给出一个数组arr,数组中每个元素都仅出现两次,除了其中一个数只出现一次,找出那个数。

思想:

主要的思想是用异或来做,两个相同的数异或后会变为0,所以对数组进行异或,最后得到的结果就是只出现一次的数。

代码:

JAVA AC 时间O(n) 空间O(1)

class Solution {
    public int singleNumber(int[] nums) {
        int len = nums.length;
        if(len<=0) return -1;
        int res = nums[0];
        for(int i=1;i<len;i++){
            res^=nums[i];
        }
        return res;
    }
}

Single Number II

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

题目描述:

与上题不一样的是,数组中元素每个都出现了3次,除了其中一个数只出现一次,找出这个数。

思想:

考虑全部用二进制表示,如果我们把第i个位置上所有数字的和对3取余,那么只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0). 因此取余的结果就是那个 “Single Number”。一个直接的实现就是用大小为 32的数组来记录所有位上的和。

代码:

C++ AC 时间O(n) 空间O(1)

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int len = nums.size();
        int res = 0;
        for(int j=0;j<32;j++){
            int sum = 0; //二进制所有数每一位的数字之和
            for(int i=0;i<len;i++){
                 sum+=((nums[i]>>j)&1);
            }
            if(sum%3==1){
                res |=1<<j;
            }
        }
        return res;
    }
};

Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

题目描述:

该题目是数组中除了其中2个数只出现一次,其他数都出现了2次,找出这2个数。

思想:

该题目类似于第一题,如果该数组只有一个数出现一次那么可以直接用题目I的逻辑来做

所以我们要对该数组进行分组,把这两个只出现一次的数分别分为A,B两组

那么如何分组呢,首先这两个数肯定是不相同的,那么我们可以把这两个数转化为2进制,进行比较。每一位进行^运算,肯定有其中一位进行^运算后结果为1.

也就是说这两个数在2进制中的这一位,一个是0,一个是1.然后找到这一位的位置,再遍历数组nums,对每个元素的这一位进行^运算,这样通过运算后为0的并入组A,为1的并入组B。

再分别对组A 和 组B进行如题目1的逻辑分别找到对应只出现一次的数。

代码:

C++ AC 时间O(1) 空间O(n)

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        vector<int> res;
        if(nums.size()<=0) return res;
        int res1=0;
        int res2=0;
        int index = findFistSum(nums);
        for(int i=0;i<nums.size();i++){
            if((nums[i]>>index)&1) {res1^=nums[i];}
            else                   {res2^=nums[i];}
        }
        res.push_back(res1);
        res.push_back(res2);
        return res;
    }
    ///返回 二个只有1唯一数异或后 他们的二进制的第一位为1的位置
    int findFistSum(vector<int>& nums){
        //所有数异或
        int res = nums[0];
        for(int i=1;i<nums.size();i++){
            res ^=nums[i];
        }
        for(int i=0;i<32;i++){
            if((res>>i)&1){
                return i;
            }
        }
    }
};


深入解析UE5内存分析:从Memreport到Unreal Insights 本文深入解析了UE5内存分析的两大核心工具:Memreport与Unreal Insights。Memreport提供详细的内存快照,帮助定位UObject等资源的内存占用;而Unreal Insights则能进行实时监控与历史回溯,精准追踪内存泄漏。掌握这两款工具是优化UE5项目性能、确保大型项目稳定运行的必备技能。 阅读详情

相关推荐

【STM32开源实战】基于STM32的智能输液监控系统设计与实现

本文详细介绍了基于STM32F103C8T6主控芯片的智能输液监控系统设计与实现。该系统通过光学液位传感器、温度传感器和红外滴速检测模块实时监测输液状态,利用步进电机自动调节滴速,并通过蓝牙实现数据远程传输,为医院提供了一套低成本、高可靠性的智能输液解决方案。

h6i7j8的博客 761

[Leetcode] Clone Graph 复制图

Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's undirected graph serialization: Nodes are labeled unique...

weixin_34310127的博客 148

【Labview】对连续采集数据的一种采样方法

图1如图1,想要对这样一个连续信号进行数据点的采集,我根据网上收集到的方法,在此分享一下最终的结果。可以拓展结合文件的写入,完成对连续信号的采集和输出。 已知: 一个连续信号,如图1. 目标: 设定一定采集点个数、采集点时间间隔、和采集周期次数,得到这条连续信号的数据点,如图2. 图2 方法如下: 主要利用的是队列的方法。 在连续信号生成的时候,不断的写入队列,并且清除队列。 ...

李时珍食疗志的博客 1万+

[leetcode 8] single-number-i-ii

题目描述: single-number-i: 现在有一个整数类型的数组,数组中素只有一个元素只出现一次,其余的元素都出现两次。 注意: 你需要给出一个线性时间复杂度的算法,你能在不使用额外内存空间的情况下解决这个问题么? Given an array of integers, every element appears twice except for one. Find that single ...

gsmaster8的博客 247

LVDS接口总结--(0)LVDS硬件电路接口

xilinx LVDS接口硬件总结

zidan1412的博客 9723

Qwen2.5-Omni实战:5分钟搞定多模态AI模型本地部署(含Thinker-Talker架构解析)

本文详细介绍了Qwen2.5-Omni多模态AI模型的本地部署流程,包括硬件配置、环境准备和实战应用开发。特别解析了其创新的Thinker-Talker架构,该架构通过TMRoPE位置编码实现跨模态同步处理,大幅提升多模态任务效率。5分钟即可完成部署,适合开发者快速实现文本、图像和音频的联合处理。

weixin_29085865的博客 172

搜索范围

给定一个按照升序排列的整数数组nums,和一个目标值target。找出给定目标值在数组中的开始位置和结束位置。 你的算法时间复杂度必须是O(logn) 级别。 如果数组中不存在目标值,返回[-1, -1]。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: [3,4] 示例2: 输入: nums = [5,7,7,8...

qq_36325159的博客 431

安信可TB蓝牙模组系列 实战Ble Mesh智能照明系统搭建

本文详细介绍了如何使用安信可TB蓝牙模组系列搭建Ble Mesh智能照明系统。从硬件准备、固件烧录到手机APP组网全流程,提供了实战步骤和优化建议,特别适合智能家居开发者入门。Ble Mesh的自组网能力解决了蓝牙传输距离限制,实现全屋灯光智能控制。

weixin_30856725的博客 353

LeetCode--single-number-ii

题目描述 Given an array of integers, every element appears threetimes except for one. Find that single one. Note:  Your algorithm should have a linear runtime complexity. Could you implem

wl_ss的博客 390

[Dify实战] OA 公文排版助手:自动格式化、编号、生成摘要-带配套资源

摘要: Dify 公文排版助手通过自动化解决公文处理中的格式混乱、编号错漏等问题。支持标题层级自动编号、摘要生成、要素补全等功能,输出标准化Markdown格式。核心流程包括输入原文、智能识别、自动排版与要素输出,适用于通知、纪要等场景。实施需统一模板规则,规范输入格式,并通过试跑优化纠错率与处理效率。关键价值在于减少人工返工,提升排版一致性,未来可对接OA系统实现全流程自动化。

技术小甜甜:传播可落地技术,帮助个人和企业降低解决真实场景问题的成本 472

【MERRA-2数据集】M2I1NXASM (5.12.4) 和 M2I1NXINT (5.12.4)概述

M2I1NXASM (5.12.4) 和 M2I1NXINT (5.12.4)概述

WW、forever的博客 683

LeetCode. Single Number I II III

找出只出现k次的单个数 位运算

grllery的博客 373

华为OD机试双机位C卷-开心消消乐(Py/Java/C/C++/Js/Go)

华为OD机试(机考)双机位C卷 【开心消消乐】,提供Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为od机试 - 开心消消乐。

qq_45776114的博客 1513

leetcode single number I II III [python]

leetcode single number的三道题目 代码及实现 总结及归纳 I.leetcode single number的三道题目 ①有一个数字出现一次,其余数字出现两次,找出此数 ②有一个数字出现一次,其余数字出现三次,找出此数 ③有两个数字均只出现一次,其余数字出现两次,找出此数 II. 代码及实现 ①class Solution(object): def single

Judewen的博客 501

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

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

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

LeetCode Single Number I / II / III

【1】LeetCode 136 Single Number 题意:奇数个数,其中除了一个数只出现一次外,其他数都是成对出现,比如1,2,2,3,3...,求出该单个数。 解法:容易想到异或的性质,两个相同的数异或为0,那么把这串数从头到尾异或起来,最后的数就是要求的那个数。 代码如下: class Solution { public: int singleNumb...

weixin_30797027的博客 130

深度学习工具包 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 Single Number I II III

Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using e

menghan1224的博客 301

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

从航天飞机STS-6任务看复杂系统集成与自主控制工程实践

在系统工程与航天技术领域,系统集成和自主控制是两大核心概念。系统集成关注如何将多个独立子系统(如推进、导航、载荷)通过精确定义的接口组合成一个协同工作的整体,其关键在于接口设计、数据协议和兼容性测试。自主控制则指系统在无人直接干预下,依靠预设算法和传感器输入,独立完成决策与执行的能力,这依赖于状态机、容错控制和实时反馈机制。这些技术的价值在于能够构建高可靠性、可应对复杂环境的智能系统,广泛应用于航天器在轨操作、无人驾驶和工业自动化等场景。以航天飞机STS-6任务为例,其成功部署TDRS-1卫星的关键,正是通

weixin_34315485的博客 387

【Leetcode】Single Number、Single Number II、Single Number III

list操作 time:O(n2);space:O(n)/O(1)time:O(n^2);space:O(n)/O(1)time:O(n2);space:O(n)/O(1) 遍历list中的每一个元素,用额外空间记录遍历的数,这个额外空间tmp初始为空,遍历时,若存在,则从tmp中删除,不存在则加入tmp,由于只有一个数只出现了一次,其他数都是两次,所以最后tmp中只剩一个元素,将其输出。 ...

Ray 309

LeetCode 【Single Number I II III】

Given an array of integers, every element appearstwiceexcept for one. Find that single one. 思路: 最经典的方法,利用两个相同的数异或结果为0的性质,则将整个数组进行异或,相同的数俩俩异或,最后得到的就是那个single number,复杂度是O(n) 代码: class Solution ...

weixin_34122604的博客 77

LeetCode Single Number I,II,III (136,137,260)

把三道 Single Number 放一起做了吧,三道都是位操作的题 136. Single Number 除了一个数,其他数都出现2次,找那个唯一的数 利用异或操作,偶数重复的元素异或结果为0,不影响 public class Solution { public int s...

chigai9787的博客 144

70 leetcode - Single Number I,II,III

leetcode中Single Number I,Single Number II,Single Number III.

忧桑的小兔子 385

Single Number I、II、III leetcode答题笔记

1. Given an array of integers, every element appears twice except for one. Find that single one. 使用按位异或操作,相同的整数,按位异或操作后为0,将数组的所有整数进行按位异或,最后的结果即出现一次的整数。 public int singleNumber(int[] nums) {

limeng120的专栏 236

[Leetcode] #136#137#260 Single Number I & II & III

Discription: Given an array of integers, every element appears twice except for one. Find that single one. Solution: 1.任何相同数异或等于0 2.0与任何数异或等于该数 3.异或的结合律 int singleNumber1(vector& nums) {

奔跑的小乌龟 367

Leetcode 136 137 260 SingleNumber I II III

Leetccode 136 SingleNumber I Given an array of integers, every element appearstwiceexcept for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you impl...

weixin_30477293的博客 115

[Leetcode学习-java]Single Number I ~ III(单独数)

Single Number I 问题: 难度:easy 说明: 给出一个非空数组,数组内只有一个元素是单独出现,其他都出现两次,找出单独出现的元素。 问题链接:https://leetcode.com/problems/single-number/ 输入案例: Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 我的代码: 第一次自己写的代码思路就很清奇,记下来是想想自己为什么这样做。

qq_28033719的博客 261

[leetcode]Single Number

刷微博时看见的一道网易面试题,竟然一点印象都没有,后来才知道是leetcode上面的原题,而且是一个系列的都是关于位运算的。136. Single Number Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorit

paine1690的博客 520
上一篇: 详解nginx反向代理+SwitchHost+Tomcat绑定域名配置总结
下一篇: TCP协议中的三次握手和四次挥手(图解)
Mike_CSU
博客等级 码龄10年 6粉丝 39原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值