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.app
找到數組中出現多餘一半的數,假設數組非空且必定存在這樣的數spa
思路以下,排序後最中間的數必定是出現超過一半的那個數code
public int majorityElement(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; }