当前位置:网站首页>Moore vote, leetcode169, leetcode229
Moore vote, leetcode169, leetcode229
2022-06-26 10:42:00 【MervynLammm】
Moore voted
A preliminary understanding
Topics involved
LeetCode 169 - Majority Element
Description of algorithm
In a given array , Find out if there are more than n/2 The elements of . The title assumes that there must be an element that appears more than n/2 Time .
Ideas
Delete two different elements in the array each time , After traversing the array , The remaining elements must be more than n/2 Secondary elements .
- Define the candidate
candGive any value 、 CountercountInitialize to0 - Traversal array
- If
countThe value is0, takecandAssign to the current valuenums[i],countThe assignment is1 - If
countValues are not for0, And current valuenums[i]be equal tocandValue , becountAdd one , otherwisecountMinus one
- If
- After traversal ,
candThat is, the element
count Subtracting one can be understood as deleting the current element in the array nums[i] And a cand The elements of , When count Element is 0 It can be understood that all the preceding numbers have offset each other .
Code implementation
public int majorityElement(int[] nums) {
int cand = 0;
int count = 0;
for (int i = 0; i< nums.length; ++i) {
if (count == 0) {
count = 1;
cand = nums[i];
continue;
}
if (cand == nums[i]) count++;
else count--;
}
return cand;
}
Advanced
Topics involved
LeetCode 229 - Majority Element II
Ideas
The topic should be found to occur more than n/3 The elements of , But there is no guarantee that the element will exist .
Delete three different elements at a time , Last of all ( Two at most ) Must be the one who appears the most , But not necessarily greater than n/3 Time , You also need to iterate over whether the array count is greater than n/3. Thus more than n/k The elements of ( most k-1 individual ).
- Define the candidate
cand1andcand2Give any value 、 Countercount1andcount2Initialize to0 - Traverse the array to find possible elements for the first time
- If the current value
nums[i]be equal tocand1orcand2Value , Correspondingcount1orcount2Add one - If
count1orcount2The value is0, takecand1orcand2Assign to the current valuenums[i], Correspondingcountassignment1 - otherwise
count1andcount2All minus one
- If the current value
count1andcount2The assignment is0- Traverse the array for the second time to determine whether the condition is met ( The frequency of occurrence is greater than
n/3)- Judge
nums[i]Whether or notcand1orcand2equal , Equal corresponds tocountAdd one
- Judge
- Eventually greater than
n/3The element of the degree is the desired
Code implementation
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<>();
if (nums.length == 0) return result;
int cand1 = 0;
int cand2 = 0;
int count1 = 0;
int count2 = 0;
for (int i = 0; i < nums.length; ++i) {
if (cand1 == nums[i]) {
count1++;
continue;
}
if (cand2 == nums[i]) {
count2++;
continue;
}
if (count1 == 0) {
count1 = 1;
cand1 = nums[i];
continue;
}
if (count2 == 0) {
count2 = 1;
cand2 = nums[i];
continue;
}
count1--;
count2--;
}
count1 = 0;
count2 = 0;
for (int i = 0; i < nums.length; ++i) {
if (cand1 == nums[i]) count1++;
else if (cand2 == nums[i]) count2++;
// must do else if, because cand1 and cand2 It could be the same element
}
if (count1 > (nums.length)/3) result.add(cand1);
if (count2 > (nums.length)/3) result.add(cand2);
return result;
}
Reference material
Moore voting algorithm ( Boyer-Moore Voting Algorithm)
边栏推荐
- SSH, SCP command appears permission denied, please try again solution
- Write data to local file
- 開發者,微服務架構到底是什麼?
- Omni channel, multi scenario and cross platform, how does app analyze channel traffic with data
- Blog article index Summary - wechat games
- 36 qtextedit control input multiline text
- Reshape a two-dimensional array with 3 rows and 3 columns to find the sum of the diagonals
- Allocation de mémoire tas lors de la création d'objets
- MySQL项目8总结
- OpenCV图像处理-灰度处理
猜你喜欢

看我在Map<String, String>集合中,存入Integer类型数据

開發者,微服務架構到底是什麼?

MySQL 8th job

Which PHP open source works deserve attention

What is in the method area - class file, class file constant pool, runtime constant pool

Développeur, quelle est l'architecture des microservices?

SwiftUI 开发经验之为离线优先的应用程序设计数据层

Call API interface to generate QR code of wechat applet with different colors

Based on Zeng Shen's explanation, the line segment tree is studied again one

Omni channel, multi scenario and cross platform, how does app analyze channel traffic with data
随机推荐
sysbench基础介绍
Search engine advanced search method records
Global and Chinese market of amateur football helmets 2022-2028: Research Report on technology, participants, trends, market size and share
MySQL 10th job - View
36 qtextedit control input multiline text
Global and Chinese market of recycled paper 2022-2028: Research Report on technology, participants, trends, market size and share
String constant pool, class constant pool, and runtime constant pool
Global and Chinese market of aluminum sunshade systems 2022-2028: Research Report on technology, participants, trends, market size and share
String class intern() method and string constant pool
When will JVM garbage collection enter the older generation
Based on Zeng Shen's explanation, the line segment tree is studied again one
Développeur, quelle est l'architecture des microservices?
1. sum of two numbers (leetcode topic)
Use of exec series functions (EXECL, execlp, execle, execv, execvp)
【無標題】
echo $?
MySQL项目7总结
Omni channel, multi scenario and cross platform, how does app analyze channel traffic with data
Oracle sqlplus 查询结果显示优化
六月集训(第26天) —— 并查集