当前位置:网站首页>Find the number that appears only once in the array
Find the number that appears only once in the array
2022-06-30 09:01:00 【Byte station】
1. subject ( difficult )
Given an array , Except for one element, only 1 Time , All the other elements appear 3 Time . Design an algorithm to find elements that only appear once . The required time complexity is O(n), Extra space O(1).
1.1 Example
Input : arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3,3}
Output : 2
except 2 Everything else 3 Time .
Input : arr[] = {10, 20, 10, 30, 10, 30, 30}
Output : 20
except 20 Everything else 3 Time .
1.2 java Code implementation
class GFG {
static int getSingle(int arr[], int n)
{
int ones = 0, twos = 0;
int common_bit_mask;
for (int i = 0; i < n; i++) {
twos = twos | (ones & arr[i]);
ones = ones ^ arr[i];
common_bit_mask = ~(ones & twos);
ones &= common_bit_mask;
twos &= common_bit_mask;
}
return ones;
}
public static void main(String args[])
{
int arr[] = { 3, 3, 2, 3 };
int n = arr.length;
System.out.println(" The element that appears only once is " + getSingle(arr, n));
}
}
Output :
The element that appears only once is 2
2. Algorithm explanation
2.1 Bitwise operation
2.1.1 And (&) Operator :
- a & b Only a、b Also for 1, be a & b = 1.1 & 1 = 1、1 & 0 = 0、0 & 1 = 0、0 & 0 = 0.
- effect : Inquire about , Find the same . Look for two numbers in common 1 Of bit position .
2.1.2 or (|) Operator :
- a | b a、b Any one for 1, be a | b = 1.1 | 1 = 1、1 | 0 = 1、0 | 1 = 1、0 | 0 = 0.
- effect : assignment . take a On And b by 1 Of bit position Corresponding bit The position is 1.
2.1.3 Not (~) Operator
- Reverse operation ,~1 = 0,~0 = 1.
- effect : combination & operation eliminate .a &= ~b.
2.1.4 Exclusive or (^)
- a ^ b Only ab Mutually exclusive , be a ^ b = 1.1 ^ 0 = 1、0 ^ 1 = 1、0 ^ 0 = 0、1 ^ 1 = 0.
- effect : Inquire about , Make a difference .
- shorthand : Complementation of yin and Yang , Only men and women can have children . Looking at the same pattern in the game repeatedly can offset .
2.2 Their thinking
Record each bit by 1 The number of times . appear 1 Secondary existence ones On . appear 2 Secondary existence twos On . appear 3 Remove... Times .
- As the required time complexity is O(n), So loop through the array .
- Set two variables ones,twos.ones The meaning is , Elements bit The bit value is 1 appear 1 Time , Assign a value to ones.ones = ones^arr[i]. twos The meaning is : If the element currently traversed bit The bit value is 1 appear 2 When the time , Assign a value to twos.
- If the element currently traversed bit The bit value is 1 There is 3 Time , Will ones and twos The bit The value on the bit is cleared .
- Final ones The value of is a number that appears only once .
A few doubts ?
- Why? ones Use XOR (^) operation ?
answer : With { 3, 3, 2, 3 } For example . First traversal ,ones = 3.* Second traversal ,arr[1] =3. ones Need to become 0. Need to offset arr[1]. It's kind of like xiaoxiaole . So use XOR operation .
- If you decide which bit values of an element are 1 Three times ?
answer :ones & twos.
calculus
With { 3, 3, 2, 3 } For example
- First cycle arr[0] = 3 .
twos = tows|(ones&arr[0])
twos = 00000000|(00000000&00000011) =00000000
ones = ones^arr[0]
ones = 00000000^00000011 = 00000011
common_bit_mask = ~(ones & twos)
common_bit_mask = ~(00000011 & 00000000) =11111111
ones & = common_bit_mask
ones = 00000011
twos & = common_bit_mask
twos = 00000000
ones = 3,twos = 0
- The second cycle arr[1] = 3 .
twos = tows|(ones&arr[1])
twos = 00000000|(00000011&00000011) =00000011
ones = ones^arr[1]
ones = 00000011^00000011 = 00000000
common_bit_mask = ~(ones & twos)
common_bit_mask = ~(00000000 & 00000011) =11111111
ones & = common_bit_mask
ones = 00000000
twos & = common_bit_mask
twos = 00000011
ones = 0,twos = 3
- The third cycle arr[2] = 2 .
twos = tows|(ones&arr[2])
twos = 00000011|(00000000&00000010) =00000011
ones = ones^arr[2]
ones = 00000000^00000010 = 00000010
common_bit_mask = ~(ones & twos)
common_bit_mask = ~(00000010 & 00000011) =11111101
ones & = common_bit_mask
ones = 00000010 & 11111101 = 00000000
twos & = common_bit_mask
twos = 00000011 & 11111101 = 00000001
ones = 0,twos = 1
- The fourth cycle arr[3] = 3 .
twos = tows|(ones&arr[3])
twos = 00000001|(00000000&00000011) =00000001
ones = ones^arr[3]
ones = 00000000^00000011 = 00000011
common_bit_mask = ~(ones & twos)
common_bit_mask = ~(00000011 & 00000001) =11111110
ones & = common_bit_mask
ones = 00000011 & 11111110 = 00000010
twos & = common_bit_mask
twos = 00000001 & 11111110 = 00000000
ones = 2,twos = 0
Welcome to the group
I set up a technology exchange group . Please add my friend , remarks " Add group ". I'll pull you into the group 
边栏推荐
- Be careful of this hole in transmittable thread local
- Redis design and Implementation (III) | interaction between server and client (event IO model)
- Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
- Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)
- 使用华为性能管理服务,按需配置采样率
- Opencv learning notes -day13 pixel value statistics calculation of maximum and minimum values, average values and standard deviations (use of minmaxloc() and meanstddev() functions)
- Introduction to the runner of mmcv
- Esp32 (4): overview of the overall code architecture
- [untitled]
- Comparaison de deux façons d'accéder à la base de données SQL Server (sqldatareader vs sqldataadapter)
猜你喜欢

Bind threads to run on a specific CPU logical kernel

2021-04-29

Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)

Use Huawei performance management service to configure the sampling rate on demand

Redis design and Implementation (I) | data structure & object

Codeworks 5 questions per day (1700 for each) - the third day

Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which

Enhance the add / delete operation of for loop & iterator delete collection elements

Detectron2 source code reading 4-- registrar construction model

100 lines of code and a voice conversation assistant
随机推荐
vim 从嫌弃到依赖(21)——跨文件搜索
Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
[untitled]
Opencv learning notes -day8 (keyboard typing (waitkey()); Wait for typing) action: triggers some action when the appropriate character is typed using the keyboard)
Mmdet line by line code interpretation of positive and negative sample sampler
Is it safe to open an account? How can anyone say that it is not reliable.
Unsupportedclassversionerror is reported when starting jar package. How to repair it
[untitled]
Is the reverse repurchase of treasury bonds absolutely safe? How to open an account online
Based on svelte3 X desktop UI component library svelte UI
酒精测试仪方案:酒精测试仪是根据什么原理测酒精溶度?
Build a docker image of Henkel database from 0
Redis design and Implementation (VI) | cluster (sharding)
Esp32 (IX): OTA function of function development
Does the oscilloscope probe affect the measurement of capacitive load?
El input limit can only input numbers
Torchvision loads the weight of RESNET except the full connection layer
Rew acoustic test (III): generate test signal
Rew acoustic test (I): microphone calibration
证券开户的优惠怎样才能得到?在线开户安全?