码迷,mamicode.com
首页 > 其他好文 > 详细

Majority Element II——LeetCode

时间:2015-06-30 07:45:12      阅读:487      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

题目大意:给定一个大小为n的数组,找出Majority元素,满足出现次数大于 ⌊ n/3 ⌋ 次。

解题思路:大于 ⌊ n/3 ⌋ 次,那么应该最多有两个Majority元素,之前有道题是找出 大于⌊ n/2 ⌋ 次Majority元素,这道题有点类似,稍微复杂一点,还是利用投票算法,count作为对元素的计数,候选元素等于当前元素则count+1,否则减1,count等于0则更换候选元素。

    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        int can1 = nums[0], can2 = nums[0], cnt1 = 1, cnt2 = 0;
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            if ((cnt1 == 0 && num != can2)) {
                can1 = num;
            } else if (cnt2 == 0 && num != can1) {
                can2 = num;
            }
            if (num == can1) {
                cnt1++;
            } else if (num == can2) {
                cnt2++;
            } else {
                cnt1--;
                cnt2--;
            }
            cnt1 = cnt1 < 0 ? 0 : cnt1;
            cnt2 = cnt2 < 0 ? 0 : cnt2;
        }
        cnt1 = 0;
        cnt2 = 0;
        for (int num : nums) {
            if (num == can1) {
                cnt1++;
            } else if (num == can2) {
                cnt2++;
            }
        }
        if (cnt1 > nums.length / 3)
            res.add(can1);
        if (cnt2 > nums.length / 3)
            res.add(can2);
        return res;
    }

 

Majority Element II——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4609251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!