当前位置:网站首页>The 21st layer of leetcode Langya list - numbers that only appear once
The 21st layer of leetcode Langya list - numbers that only appear once
2022-06-10 08:53:00 【Javanese aborigines, joelib】
LeetCode The 21st floor of Langya list - A number that appears only once ( Binary algorithm )
List of articles
subject
Title browsing

Key information extraction
Except that an element only appears once , The others appeared three times2e-31 <= nums[i] <= 2e31 - 1The time complexity of the algorithm should be linear
Topic information interpretation
- In the array , There are only two possible situations
- A certain element has been thought about three times
- A certain element is thought of once
- The value range of each element is in one
intWithin the scope of
Description of algorithm
Hash counting method
- There are two main types of hash counting
- adopt
HashSetSet to count , Generally, this set deals with elements that have been thought of many times - adopt
HashMapSet to count , Generally, this collection deals with elements that only appear once - Obviously , What we use here is **
HashMap** Set to count
- adopt
Binary solution
- This method is very wonderful , Belong to us Force buckle 20 layers One of the Prepositive method
Algorithm details
Algorithmic thought
Hash counting method
- Let's go through it once
nums Array, Through oneHashMapTo record the number of occurrences of each element - Go over it again
HashMap, Find the element that only appears once
Binary solution

analysis
- The breakthrough of this algorithm is our
Binary digit, So we first get the of each elementBinary digit, And align its position - Aim at Elements that have appeared three times , their
Binary digitIt must be the same , That is, the following... Will appear on the corresponding binary bit Two cases1 + 1 + 1 = 3 % 3 = 00 + 0 + 0 = 0 % 3 = 0
- In either case it is 3 Multiple , The same reasoning goes to all elements that have appeared three times , As long as this element It has appeared three times on the corresponding binary bit
%3It must be equal to 0 - If the final result
(res = sum % 3) != 0, explain , This res It must have happened once Binary digit , Record these binary bits to get the number that has appeared once
Code implementation and Analysis
Hash counting method
class Solution {
public int singleNumber(int[] nums) {
var map = new HashMap<Integer,Integer>();
var target = 0;
for (var num : nums) {
// If the element doesn't exist , It is assigned as 0+1, Otherwise it is the original size +1
map.put(num,map.getOrDefault(num,0) + 1);
}
for (var res : map.entrySet()) {
if (res.getValue() == 1) {
target = res.getKey();
break;
}
}
return target;
}
}
Binary solution
class Solution {
public int singleNumber(int[] nums) {
// target Used to record the final results
var target = 0;
// Every element is in int Within the scope of , So there is 32 individual bit position , loop 32 Time
for (int i = 0; i < 32; i++) {
// Record the sum of each binary bit
var sum = 0;
for (var num : nums) {
// Get the sum of each binary bit , For details, please see the analysis 1
sum += (num >> i) & 1;
}
// For details, please see the analysis 2
if (sum % 3 != 0) {
target |= (1 << i);
}
}
// Return the result
return target;
}
}
analysis 1
- When we want to get a binary bit, the simplest way is
Shift operator >> or <<, First movei = 0position , Second movei = 1position , Just right The first and second bits are taken to , The same goes for the back - On this basis , We need to
For the result &1, There may be 1 Remove the binary bits of , Only the corresponding one - Superposition is enough
analysis 2
- There can only be two binary cases of elements that have occurred once , namely
0 and 1- If it is
0, resultsum % 3 == 0establish , This binary bit defaults to 0, There is no need to change - If it is
1, resultsum % 3 == 0Don't set up , This binary bit defaults to 0, It needs to be changed to 1, So in the end, as long as the change is1The situation of
- If it is
- take
1<<iYou can get the corresponding binary bit
Algorithm conclusion
The binary solution is superior to the hash counting method , If you don't believe me, you can verify it
The binary solution can not only be used in this problem , It can also be used in the 20 layers of force buckle !
边栏推荐
- vscode-markdown all in one-keyboard shortcut
- 想转行,为什么首选软件测试?
- Actual use of runloop
- Unzip the jar package and modify the configuration file (unzip, modify, compress and run)
- CString字符串分割函数
- The R language uses the PDF function to save the visual image results to the PDF file, uses the PDF function to open the image device, and uses the dev.off function to close the image device
- How to open an account for your own stock trading? Is it safe?
- Task06: Autumn move script C
- Uniapp always locates the chat page to the bottom display
- 视频|乐鑫研发说
猜你喜欢

How much do you need to learn before you can find a job in the software test of zero foundation career transition

Textstudio displays line numbers and does not check spelling settings

Exemple de référence AWS IOT de lexine pour esp32 - C3

数据库视图、索引、存储过程、触发器简单创建

第2章 数据的表示和运算

零基础转行软件测试需要学到什么程度才能找工作

A must visit museum in London recommended by: London Museum of natural history

从零到一,一站式解决Linux环境下的MySQL(下载篇)

Add cache like silk to optimize service

Rendercylinder lights for VTK learning
随机推荐
华为软件测试面试题 | 一位华为入职成功者的分享【笔试题】
Lexin's latest support for zephyr
Mmsegment Series III (basic network architecture and pre training model)
The tab1 function in the epidisplay package of R language calculates the frequency of vector data and visualizes it (one-dimensional frequency table, frequency percentage, cumulative percentage, using
Harmonyos (Hongmeng) collects the most complete resources in the whole network, sorts out hematemesis, and collects them quickly!
The R language uses the PDF function to save the visual image results to the PDF file, uses the PDF function to open the image device, and uses the dev.off function to close the image device
vtk学习之texture纹理映射
SAAS服务能有哪些优势
MMSegmention系列之三(基本的网络架构和预训练模型)
YAML基本语法
texstudio 如何编译运行基于markdown宏包的tex文件
Formula Derivation
Coordinate system of VTK learning
数据库视图、索引、存储过程、触发器简单创建
Oracle SQL command line (III. addition, deletion, modification and query)
Test preparation computer level 2 database day 5
Mmsegment Series IV (custom dataset)
R语言caTools包进行数据划分、scale函数进行数据缩放、class包的knn函数构建K近邻分类器、比较不同K值超参数下模型准确率和误分类率(miss classification error)
vtk学习之Pipeline管线
在 Kubernetes 中基于 StatefulSet 部署 MySQL(下)