Accepted java solution


  • -7
    S

    public class Solution {

    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        Arrays.sort(nums);
        int len = nums.length;
        int now = 1;
        
        if(len ==1) {
            res.add(nums[0]);
            return res;
        }
        
        if(len ==2) {
            if(nums[0]!=nums[1]) {
            res.add(nums[0]);
            res.add(nums[1]);
            } else {
                res.add(nums[0]);
            }
            return res;
        }
        
        for(int i=1;i<len;i++) {
            if(nums[i]==nums[i-1]) {
                now++;
                if(i == len-1&&now>len/3) {
                    res.add(nums[i-1]);
                }
            } else {
                if(now>len/3) {
                    res.add(nums[i-1]);
                } 
                    now=1;
                
            }
        }
        return res;
    }
    

    }


  • 0
    R

    I think it is not linear cause Arrays.sort() is nlogn


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.