Majority Element
链接
https://leetcode.com/problems/majority-element/#/description
描述
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.You may assume that the array is non-empty and the majority element always exist in the array.
解题思路:
因为数组中存在一个元素,其出现次数大于n/2,所以如果为元素进行计数(计数方法:如果该元素与正被计数元素相同,计数加一,如果不同则减一,如果计数器为0,则正被计数元素替换成当前元素)。经过这样的计数之后,最后正被计数的元素就是出现次数大于n/2的元素。
代码如下:
public class Solution {
public int majorityElement(int[] nums) {
int cur=0,counter=0;
for(int num:nums){
if(counter==0){
cur=num;
counter++;
}else{
if(cur==num)
counter++;
else
counter--;
}
}
return cur;
}
}
Majority Element II
url
https://leetcode.com/problems/majority-element-ii/#/description
描述
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
解题思路
解题基本思路和“Majority Element”类似,不同之处在于:
1.此题有两个正被计数的元素和两个计数器;
2.计数过程中,如果当前元素等于第一个正在被计数的元素,则counter++;如果当前元素等于第二个正在被计数的元素,则counter++;如果第一个计数器为0,则用当前元素替换第一个正被计数的元素;如果第二个计数器为0则用当前元素替换第二个正被计数的元素。
3.在计数完成之后,再此检查所得到的两个元素是否出现次数超过n/3.
代码如下:
public class Solution {
public List<Integer> majorityElement(int[] nums) {
int cur1=0,cur2=0,counter1=0,counter2=0;
for(int num:nums){
if(cur1==num){
counter1++;
}else if(cur2==num){
counter2++;
}else if(counter1==0){
cur1=num;
counter1++;
}else if(counter2==0){
cur2=num;
counter2++;
}else{
counter1--;
counter2--;
}
}
counter1=0;
counter2=0;
for(int num:nums){
if(num==cur1) counter1++;
else if(num==cur2) counter2++;
}
int len = nums.length;
List<Integer> list = new ArrayList<>();
if(counter1>len/3){
list.add(cur1);
}
if(counter2>len/3){
list.add(cur2);
}
return list;
}
}