Majority Element - Not enough test cases


  • 0
    H

    I think Majority Element problem must have lacked some test cases.

    First, I tried HashMap and then it works well for all cases even though it runs at a slower pace. Then I tried using mergesort and return the middle elements of the array as described below:

    public class Solution {
    public int majorityElement(int[] nums) {
    if(nums.length == 0) {
    return 0;
    }
    if(nums.length == 1) {
    return nums[0];
    }
    Arrays.sort(nums);
    return nums[(nums.length/2)];
    }
    }

    If we take into consideration the test case: [1,2,3,3,4,4,4], the output must be 4 because 4 appears 3 times, more than size/2 (7/2 = 3). However, if we use the above code, the answer will be nums[3] = 3, which contradicts our expected output. I submitted the above code and it is still accepted. Could anyone please explain to me if anything goes wrong.


Log in to reply
 

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