题目描述:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
解题思路:
要找出现次数大于⌊ n/2 ⌋的元素,很容易想到如果数组是有序的,直接取index为⌊ n/2 ⌋的元素便是。
Code:
class Solution {
public int majorityElement(int[] nums) {
if (nums.length == 0 || nums == null) {
return 0;
}
Arrays.sort(nums);
return nums[(nums.length-1)/2];
}
}