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.
I used a shortcut for this problem: sorting the elements, ensuring the middle numbers were the majority. I also briefly recalled the implementation of quicksort (which I haven't written here).
Another solution is to use a voting method, which I've also included here. (I didn't write this.)
public class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); return nums[nums.length / 2]; } } public class Solution { public int majorityElement(int[] num) { int major=num[0], count = 1; for(int i=1; i This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:
Original author:Jake Tao,source:「LeetCode – 169. Majority Element」