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

• ``````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...

• This post is deleted!

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.

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

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

• 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.

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

• It do return 0 :)

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