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

[LeetCode 229] Majority element II

时间:2015-09-02 08:15:45      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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.


Solution:

At most has two elements in the result, can use two counter to record occurrence. Then calculate if match the condition.

public List<Integer> majorityElement(int[] nums) {
        List<Integer> result = new ArrayList<>();
        if(nums.length==0) return result;
        int n1 = nums[0];
        int n2 = 0;
        int count1 = 1;
        int count2 = 0;
        for(int i=1;i<nums.length;i++){
            if(nums[i] == n1){
                count1++;
            }else if(nums[i] == n2){
                count2++;
            }else{
                if(count1 == 0){
                    n1 = nums[i];
                    count1++;
                }else if(count2 == 0){
                    n2 = nums[i];
                    count2++;
                }else{
                count1--;
                count2--;
            }
            }
        }
        count1 = 0;
        count2 = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i] == n1) count1++;
            if(nums[i] == n2) count2++;
        }
        if(count1>nums.length/3) result.add(n1);
        if(n1 == n2) return result;
        if(count2>nums.length/3) result.add(n2);
        return result;
    }



版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode 229] Majority element II

标签:leetcode

原文地址:http://blog.csdn.net/sbitswc/article/details/48173241

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