LeetCode-Majority Element II (JAVA)

Given an integer array of size n, find all elements that appear more
than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3] Output: [3] Example 2:

Input: [1,1,1,3,3,2,2,2] Output: [1,2]

题目:求解数组中数字出现次数大于n/3的数字,线性时间复杂度以及O(1)的空间

这是array类的题目中做过的最有心机的一道题,对时间的线性要求以及不能使用数字决定了这道题一定是有窍门的,这就是出现次数要大于n/3,这样的数字如果存在的话,顶多会有两个。
使用两个临时变量num1和num2作为出现次数最多的两个数,以及c1和c2分别记录出现次数,第一次遍历数组时,当num1出现是c1++,当num2出现时,c2++,都没有出现时,c1–,c2–。这样遍历过一遍数组后,如果存在符合条件的数字,由于她的出现次数大于1/3,所以num1或num2中肯定会存在一个。

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> ret = new ArrayList();
        int n = nums.length;
        if(n < 1) {
             return ret;
        }
        
        
        int times = n/3;
        int num1 = nums[0];
        int num2 = nums[0];
        int c1 = 0;
        int c2 = 0;
        
        for(int i = 0; i < n ; i++) {
            if(num2 != nums[i] && (c1 == 0 || num1 == nums[i])) {
                c1++;
                num1=nums[i];
            } else if(c2 == 0 || num2 == nums[i]) {
                c2++;
                num2 = nums[i];
            } else {
                c1--;
                c2--;
            }
        }
        
        c1= 0;
        c2 = 0;
        for(int i = 0; i < n ; i++) {
            if(nums[i] == num1) {
                c1++;
            } else if(nums[i] == num2) {
                c2++;
            }
        }
        
        if(c1 > times) {
            ret.add(num1);
        }
        
        if(c2 > times ) {
            ret.add(num2);
        }
        return ret;
        
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值