My java solution,easy to understand


  • -3
    J
    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
            List<Integer> res=new ArrayList<Integer>();
            if(nums.length==0||nums==null) return res;
            int len=nums.length/3;
            Arrays.sort(nums);
            for(int i=0;i<nums.length;i++){
                if((i+len)<nums.length&&nums[i]==nums[i+len]){
                    res.add(nums[i]);
                    int k=i+1;
                    while(k<nums.length&&nums[k-1]==nums[k])k++;
                    i=k-1;
                }
            }
            return res; 
        }
    }

  • 0
    I

    When you use Arrays.sort, you algorithm is not in linear time anymore.


Log in to reply
 

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