Easy Solution(JAVA)


  • 0
    M

    We sort the array first. So if any element appears more than n/3 times then that particular number will be present at n/3 th position from the first occurence of that number.

    class Solution {
        public List<Integer> majorityElement(int[] nums) {
            
                Arrays.sort(nums);
                int i=0,count = nums.length/3;
                List<Integer> list = new ArrayList();
            if(nums.length<3){
                for(int j=0;j<nums.length;j++){
                    if(!list.contains(nums[j]))
                        list.add(nums[j]);
                }
                return list;
            }
                while(i+count<nums.length){
                    if(nums[i+count]==nums[i]){
                        if(!list.contains(nums[i])){
                            list.add(nums[i]);
                        }
                        i = i+count;
                    }
                    else{
                        i++;
                    }
                }
                return list;
           
        }
    }
    

Log in to reply
 

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