Leetcode: Majority Element &Majority Element II

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值