LeetCode- Bit Manipulation LeetCode总结(1) —— 位运算

算法技巧-位运算(Bit Manipulation) 算法技巧-位运算(Bit Manipulation)一 . 位运算简介二 . 位运算规则A . AND与运算B . OR或运算C . XOR异或运算D . NOT取反运算E . 位移运算三 . 位运算技巧A . AND与运算技巧1 . 清零B . OR或运算技巧C . XOR异或运算技巧D . NOT取反运算技巧E . 位移运算技巧F . 综合运算技巧四 . 位运算例题五 . 位运算资料A . 关... 阅读详情
Bit Manipulation(位运算):主要思想参考《剑指Offer》第二章2.4.3节。
       一共五种运算:与,或,异或,左移,右移。
 
常用技巧:
(1)n & (n-1)能够消灭n中最右侧的一个1。
(2) 右移:除以2, 左移:乘以2。
(3)异或性质:交换律,0^a=a, a^a=0;
(3)将常用字符、数字等均转为按位运算,可以节约空间。

LeetCode题目解析

  1. 使用右移。
  2. 使用n&(n-1)可以消灭一个1的性质来求解。

                使用n&(n-1)=0来判断。
                注意0和负数的情况。

                使用右移和左移。

             求解出现次数大于n/2的数字。
    •  按照顺序循环,如果两个元素不相等,则删除这两个元素。则剩下的为出现大于n/2次的那个元素。
    •  使用sort的解决方法,耗时48ms。
    •  不进行实质的删除操作,只是做mark而已。
    •  位运算方法:统计32位每个位上出现1的次数大于n/2的,如果是则直接赋值为1,否则为0。

  • 其他算法


            数组中,只有一个数出现一次,其余数均出现两次。求出现一次的那个值。
            了解异或的三个性质:
              //主要思想:   
        //   异或满足交换律,a1 ^ a2 ^ .... ^ an ^ a1 ^ .... ^ an-1 = (a1^a1)^(a2 ^a2) ^(....) ^(an-1 ^ an-1) ^ an   
        //    a ^ a = 0;   
        //    a ^ 0 = a;   
        显然将所有数字异或后,得到的结果即为出现一次的值。

        扩展:
                有两个出现一次的数字,其余都出现两次。找出这两个出现一次的数字。
  1. 将所有数字做异或运算,按照异或结果中1的位置将数组分成两组。(因为1的位置表示有不同的取值)
  2. 对两组分别求一次异或,值不为0,则为求得的结果。

            找出现一次的元素,其余元素均出现三次。
            将每个元素的每一位分别相加,取模3,则会得到该位的取值,原理类似于(3(a1+a2+...+an)+a)%3 = a;
        
            扩展:
            可以扩展到K(元素出现K次,只有一个出现一次)的做法:
                    1、K为偶数:参考  Single Number 的做法;
                    2、K为奇数:参考  Single Number II 的做法;

78       Subsets                          http://blog.csdn.net/xsloop/article/details/47003033
            求全组合。
            对于全组合,也就是对于N个元素,如果元素出现则用1表示,不出现则用0;
            那么,得到的组合序列是2^N, 其中0表示所有元素都不取,1表示只取第一个,。。。。。
            这样可以位运算的方法得到一个数组中的所有组合。
            给两个数M, N, (0<=M <=N<=INT_MAX),求M,N中所有数字的按位与运算。
            将M和N分别按位移动,直到M和N相等,记录移动的位数count,则返回值为M<<count;
            如果M和N始终不相等,则返回0;

            使用位运算计算DNA序列中重复的10个字符组合。
            DNA只有四个字符,分别用00, 01, 10, 11表示;
            10个字符需要2^20位,2^20 = 1024 *1024,则只需要即可1024*1024的哈希表即可。
             对于字符串,从头开始以10个字符为单位,统计出现的结果放入哈希表中,当出现次数大于1则保存到重复dna序列中。


Windows平台无人机仿真:从零搭建SITL环境与QGC联调 本文详细指导了在Windows平台上从零搭建无人机软件在环(SITL)仿真环境,并与QGroundControl(QGC)进行联调的完整流程。通过使用Cygwin工具链,开发者可以在没有实体硬件的情况下,模拟运行ArduPilot飞控,并通过MAVLink协议连接QGC地面站进行全功能测试,为无人机软件开发提供了一个安全、经济的虚拟沙盒环境。 阅读详情

相关推荐

Qlib+backtrader:2014.1.1-2023.9.20最新回测结果,可以实盘吗?

今年以来,在研究了qlib和backtrader的基础上,把二者结合起来进行了一个策略研究。简单说就是用qlib在200只股票的股票池中进行滚动训练与预测(walk forward),总体数据范围是2005到2023年,以20日间隔滚动训练和预测,最终得到2014.1.1-2023.9.20共10年测试期的收益率预测结果。将预测结果代入backtrader进行回测,得到如下回测结果。

qtbgo的博客 1786

LeetCode--位运算篇

因为热爱所以坚持,因为热爱所以等待。熬过漫长无戏可演的日子,终于换来了人生的春天,共勉!!! 位运算 基本原理 0s 表示一串 0,1s 表示一串 1。 x ^ 0s = x x & 0s = 0 x | 0s = x x ^ 1s = ~x x & 1s = x x | 1s = 1s x ^ x = 0 x & x = x x | x = x 位与运算技巧 n&(n-1) 去除 n 的位级表示中最.

Free的午后 882

Windows本地化部署Dify完整指南

本文详细介绍了在Windows系统上本地化部署Dify的完整步骤,涵盖了Docker Desktop的安装与配置、Dify源代码的获取、环境变量的设置、服务的启动与管理、以及常见问题的解决方案。文章首先指导用户如何下载和安装Docker Desktop,并配置WSL 2功能。接着,详细说明了如何获取Dify源代码,并通过Docker Compose启动服务。文章还提供了高级配置指南,包括如何配置大语言模型和更新Dify版本。最后,针对Docker镜像拉取失败等常见问题,提供了详细的诊断和解决方案。通过本文,

jacky_zhuyuanlu的博客 1万+

LeetCode——位运算

LeetCode——位运算

qq_43332536的博客 626

历史预测+LLM双杀!DriveGPT4-V2闭环驾驶配置避坑指南

本文深入探讨了DriveGPT4-V2在工程化部署中的核心挑战与解决方案。通过融合历史轨迹预测与大语言模型,该模型旨在实现更可靠的端到端自动驾驶。文章详细解析了从环境配置、多模态Token对齐、轻量控制头设计到训练优化与闭环仿真验证的全流程,为开发者提供了一份详实的避坑指南。

transformer2023的博客 388

【多媒体交互】Unity+普通摄像头实现UI事件分析

利用摄像头捕捉用户的手势或动作,结合坐标映射与事件系统触发UI交互

qq_38350004的博客 1334

LeetCode常见题型——位运算

位运算是算法题里比较特殊的一种类型,它们利用二进制位运算的特性进行一些奇妙的优化 和计算。

贫道绝缘子的博客 682

单细胞转录组分析(scRNA-seq)

单细胞转录组测序(Single-cell RNA sequencing,scRNA-seq)是一种高通量测序技术,可以在单细胞水平解析基因表达情况,揭示细胞异质性,探索稀有细胞类型,并研究细胞状态转换及动态调控机制。与传统的。

大甘的博客 6164

LeetCode刷题——位运算相关

LeetCode位运算相关题目

ha_lee的博客 1828

MIPI转LVDS芯片调试实战:从Kernel到UEFI的完整点亮流程

本文详细解析了MIPI转LVDS芯片调试的全流程,从Kernel驱动开发到UEFI早期初始化,涵盖I2C通信、电源时序控制等核心挑战。通过LT9211芯片实战案例,提供设备树配置、电源时序优化及显示异常排查等实用技巧,助力工程师高效完成屏幕调试工作。

weixin_30314813的博客 455

曲线生成 | 图解B样条曲线生成原理(附ROS C++/Python/Matlab仿真)

本文分插值和近似两个方面介绍B样条曲线的控制点计算,以及曲线生成原理,并给出ROS C++/Python/Matlab三种实现加深理解

FRIGIDWINTER的博客 6619

【leetcode题解】位运算

:有0即0 |:有1即1 ^:相同为0,相异为1/无进位相加。解法二:高斯求和 return (5+1)(0+5)/2-sum。2. 给一个数n,确定它的二进制表示中的第x位是0还是1。解法一:哈希表(时空复杂度均为O(n))hash[26]将最右侧的1转为0,右边区域(包含1)全部取反。3. 将一个数n的二进制表示的第x位修改成1。4. 将一个数n的二进制表示的第x位修改成0。5. 提取一个数(n)二进制表示中最右侧的1。6. 干掉一个数(n)二进制表示中最右侧的1。

2301_80802299的博客 994

MIPI D-PHY TX 一致性测试实例解析 Part 02

如果测过1.3.x,并对这组测试的细节已经熟悉的前提下,1.4.x的测试将会变得轻松,因为几乎相同的测试项被用于时钟通道的数据测量。

一只豌豆象的博客 8339

LeetCode(剑指offer-bit manipulation(位运算))-面试题15. 二进制中1的个数

请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。 示例 1: 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 示例 2: 输入:00000...

qq_38236744的博客 323

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

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

Hamming Distance位运算基础问题--力扣101算法题解笔记

给定两个十进制数字,求他们二进制表示的汉明距离(Hamming Distance, 即不同位的个数)

c3152144837的博客 54

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

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

LeetCode——461.汉明距离JS

链接:https://leetcode-cn.com/problems/hamming-distance。著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。上面的箭头指出了对应二进制位不同的位置。🟣 前端2026最新【持续更新】→。输入: x = 1, y = 4。来源:力扣(LeetCode)🟢 前端0到1【持续更新】→。🔵 前端进阶【持续更新】→。🔴 AI最新学习资料 →。

zhang1339435196的博客 313

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode上的Bit Manipulation(位运算)类型的题目

文章目录Easy461. Hamming Distance两个数字的汉明距476. Number Complement 求补码136. Single Number693. Binary Number with Alternating Bits 相互交错的位信息389. Find the Difference Easy 461. Hamming Distance两个数字的汉明距 461. Hamm...

notHeadache的博客 729

leetcode算法题--二进制中1的个数

原文链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/ 逐位运算 int hammingWeight(uint32_t n) { int count = 0; while (n) { count += n & 1; n >>= 1; } return count; }

bob的博客 231

day91(2.20)——leetcode面试经典150

【代码】day90(2.19)——leetcode面试经典150。

2401_82757880的博客 234

Leetcode 位运算知识点总结

一个颇有好感的爱豆今天入伍了,人品和才华都没的说,但是因为这样或那样的原因,最终不得已提前进了部队,挺心疼他的。明年年底见吧。 昨天刷B站,看到国内一个练习生选秀节目中舞蹈导师批评国内练习生各种借口各种不努力,不禁感慨国内娱乐圈来钱太容易了。韩国爱豆生存压力大,每年出道的团很多,但是最后活下来的就那么几个。所以为了成功,他们需要不断努力不停练习,最终的表现和国内高下立判。 环境是很大的一个方面...

大锅八十小锅四十 621

力扣刷题记录&整理——(十八)Bit Manipulation

整理力扣刷题思路。语言:python题库:来自neetcode:link。

Z_zat的博客 1025

LeetCode分类刷题(一):位操作(Bit Manipulation)

位运算(Bit Manipulation)一直是程序员面试中的一个必须准备的主题, 不过现在面试中位运算出现的次数并不多,主要原因还是位运算太考察技巧了,很多时候很难在短时间内想出来,所以作为面试的题目显得有点太花时间了。 位运算的主要思想是五种运算:与(&amp;),或(|),异或(^),左移(&lt;&lt;),右移(&gt;&gt;)。 位运算的常用技巧如下: n &amp;(n-1)能...

pushup8的博客 1万+

LeetCode之Bit Manipulation题目汇总

Bitwise AND of Numbers RangeGiven a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.For example, given the range [5, 7], you should return 4

Yano_nankai的博客 1119

【LeetCode】位运算 bit manipulation(共32题)

【78】Subsets 给了一个 distinct 的数组,返回它所有的子集。 Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] 题解:我是直接dfs(backtracking)了...

weixin_30498921的博客 148

位运算(Bit Manipulation)在算法中的应用

最近刷LettCode,遇到几个没思路的算法题,都是关于位运算的 # 136 Single Number Given anon-emptyarray of integers, every element appearstwiceexcept for one. Find that single one. Note: Your algorithm should ha...

bailian1957的博客 293

Leetcode Bit Manipulation 题型总结

Leetcode 136. Single Number https://leetcode.com/problems/single-number/ 137. Single Number II https://leetcode.com/problems/single-number-ii/ 260. Single Number III https://leetcode.com/proble

Hanwenwangad的专栏 431
上一篇: LeetCode || Repeated DNA Sequences
下一篇: LeetCode || Delete Node in a Linked List
xuxumoi
博客等级 码龄16年 16粉丝 151原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值