当前位置:网站首页>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)
边栏推荐
- MySQL第七次作业-更新数据
- [sans titre]
- JS reverse | four libraries and one platform response data encryption
- Global and Chinese market for change and configuration management software 2022-2028: Research Report on technology, participants, trends, market size and share
- Express (I) - easy to get started
- DBSCAN
- Omni channel, multi scenario and cross platform, how does app analyze channel traffic with data
- Global and Chinese market of amateur football helmets 2022-2028: Research Report on technology, participants, trends, market size and share
- Concise course of probability theory and statistics in engineering mathematics second edition review outline
- Pit record_ TreeSet custom sorting results in less data loss
猜你喜欢

Swiftui development experience: data layer of application design for offline priority

MySQL第十三次作业-事务管理

MySQL 8th job

See how I store integer data in the map < string, string > set

Little red book - Summary of internal sales spike project

Problems encountered in the application and development of Hongmeng and some roast

創建對象的時候堆內存的分配

【软件项目管理】期末复习知识点整理

The sixth MySQL job - query data - multiple conditions

Use of exec series functions (EXECL, execlp, execle, execv, execvp)
随机推荐
Notes - simple but adequate series_ KVM quick start
Reshape a two-dimensional array with 3 rows and 3 columns to find the sum of the diagonals
RDB持久化验证测试
Global and Chinese market of contemporary lampshade 2022-2028: Research Report on technology, participants, trends, market size and share
Common interview questions of binary tree
Index summary of blog articles -- Industrial Internet
Using foreach to loop two-dimensional array
String class intern() method and string constant pool
Global and Chinese market of aluminum sunshade systems 2022-2028: Research Report on technology, participants, trends, market size and share
Leetcode intermediate node of linked list
Global and Chinese market for baked potato chips 2022-2028: Research Report on technology, participants, trends, market size and share
sysbench基础介绍
[online simulation] Arduino uno PWM controls the speed of DC motor
Procedure Call Standard
MySQL第七次作业-更新数据
MySQL第十一作業-視圖的應用
RDB persistence validation test
Record the handling of oom problems caused by too many threads at one time
开发者,微服务架构到底是什么?
Linux下安裝Mysql【詳細】