2 lines JAVA, using sort O(n log(n))


  • 9
    R
    public class Solution {
        public int majorityElement(int[] nums) {
            Arrays.sort(nums);
            return nums[nums.length/2];
        }
    }
    

    Worth mentioning is to check Moore's voting mechanism as well (O(n)). But anyway, two lines and especially the beauty of the second one...


  • 0
    E
    This post is deleted!

  • 0
    G

    maybe add:

    if (nums.length % 2 == 0 && nums.length - 1 >= 0 && nums[0] == nums[nums.length - 1] ) return nuts[0];

    ?

    But it makes the two lines code not clear any more.


  • 0
    E

    never mind. Since one of the condition is that the majority element appears more than ⌊ n/2 ⌋ times, nums[nums.length/2] will work.


  • 0
    G

    it dosen't return right answer with input {0,0,0,0,1,2,3,4}


  • 0
    B

    Your input is wrong. There is no enough majority numbers.
    The number of “0” is 4. Length/2 is 8/4 which is 4 as well.
    As is said in the question, the number of the majority element must MORE THAN length/2.


  • 0
    B

    how about the input is {0,0,0,0,1,2,3,0}


  • 0
    B

    It do return 0 :)


Log in to reply
 

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