Accepted Java Solution


  • -2
    C
    public class Solution 
    {
        public List<Integer> majorityElement(int[] nums)
        {
            List<Integer> ans = new ArrayList<Integer>();
            int len = nums.length;
            if(len == 0)
                return ans;
            Arrays.sort(nums);
            int cur = nums[0];
            int count = 1;
            for(int i = 1; i < nums.length; i++)
            {
                if(nums[i] == cur)
                    count++;
                else if(count > (len/3))
                {
                    ans.add(cur);
                    cur = nums[i];
                    count = 1;
                }
                else
                {
                    cur = nums[i];
                    count = 1;
                }
            }
            if(count > (len/3))
                ans.add(cur);
            return ans;
        }
    }

  • 0
    D

    Arrays.sort(nums) is not O(n).


  • 0
    O

    please answer me !! he asked for O(1) complexity but you are making for loop which will bring a complexity of O(n) right ?


  • 0
    R

    O(1) space complexity not time complexity


Log in to reply
 

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