版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35508033/article/details/89044565
求众数I
https://leetcode-cn.com/problems/majority-element/
如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多
在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时
若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字
并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可
class Solution {
public int majorityElement(int[] nums) {
int count=0,result=nums[0];
for(int i=0;i<nums.length;i++){
if(count==0){
count=1;
result=nums[i];
}else if(nums[i]==result){
count++;
}else{
count--;
}
}
return result;
}
}
求众数II
https://leetcode-cn.com/problems/majority-element-ii/
//找出的是出现次数大于n/3的元素,因此最多只可能存在两个这样的元素,而且要求O(1)的空间复杂度,因此只能使用摩尔投票法
//记变量n1, n2为候选众数; c1, c2为它们对应的出现次数
//遍历数组,记当前数字为num
//若num与n1或n2相同,则将其对应的出现次数加1
//否则,若c1或c2为0,则将其置为1,对应的候选众数置为num
//否则,将c1与c2分别减1
//最后,再统计一次候选众数在数组中出现的次数,若满足要求,则返回之
//我们使用投票法的核心是找出两个候选众数进行投票,需要两遍遍历,第一遍历找出两个候选众数
//第二遍遍历重新投票验证这两个候选众数是否为众数即可,选候选众数方法和前面那篇Majority Element 求众数一样
//由于之前那题题目中限定了一定会有众数存在,故而省略了验证候选众数的步骤,这道题却没有这种限定,即满足要求的众数可能不存在,所以要有验证
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> list=new ArrayList<>();
if(nums==null||nums.length==0){
return list;
}
int n1=0,n2=0,c1=0,c2=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==n1){
c1++;
}else if(nums[i]==n2){
c2++;
}else if(c1==0){
c1=1;
n1=nums[i];
}else if(c2==0){
c2=1;
n2=nums[i];
}else{
c1--;
c2--;
}
}
c1=0;
c2=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==n1){
c1++;
}else if(nums[i]==n2){
c2++;
}
}
if(c1*3>nums.length){
list.add(n1);
}
if(c2*3>nums.length){
list.add(n2);
}
return list;
}
}