[Leetcode] 主元问题

leetcode中有两个题目是讲这个问题的。

Majority Element II

Majority Element

区别是对于主元的个数多少上,一个,两个,三个

这里的陷阱是:当一个元素处于未设置状态的时候,是否要对他进行设置?
如果另一个元素也是未设置状态那么肯定可以设置;如果另一个元素不是未设置状态,那么在这里需要首先监测一下是否和另外那一个元素是相等的,如果是相等,那么不能对这个元素进行设置。

 1 public class Solution {
 2     public List<Integer> majorityElement(int[] nums) {
 3         List<Integer> res = new LinkedList<Integer>();
 4         int count1=0,pre1=0,count2=0,pre2=0;
 5         for(int i=0;i<nums.length;i++){
 6             int num = nums[i];
         //如果pre1没有设置,需要考虑两种情况
         //1. pre2也没有设置 2. pre2虽然设置了,但是和当前值不相等。
7 if((count1==0&&(count2==0||(pre2!=num)))||pre1==num){ 8 pre1=num; 9 count1++; 10 }else if(count2==0||pre2==num){ 11 pre2=num; 12 count2++; 13 }else{ 14 count1--; 15 count2--; 16 } 17 } 18 if(count1!=0){ 19 int count = 0; 20 for(int i=0;i<nums.length;i++){ 21 if(nums[i]==pre1) count++; 22 } 23 if(3*count>nums.length) 24 res.add(pre1); 25 } 26 if(count2!=0){ 27 int count = 0; 28 for(int i=0;i<nums.length;i++){ 29 if(nums[i]==pre2) count++; 30 } 31 if(3*count>nums.length) 32 res.add(pre2); 33 } 34 return res; 35 } 36 }

 

转载于:https://www.cnblogs.com/deepblueme/p/4779504.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值