MajorityElement2 [source code]
public class MajorityElement2 {
public int majorityElement(int[] nums) {
int mid = nums.length / 2;
Arrays.sort(nums);
return nums[mid];
}
}
用 median 思路来做, 但是不尝试实现median of medians那个算法; 就用普通的 sort;
这个的速度是3ms, 46%, 不是最优解, 但是也比之前用 map 做的要快的多了. 不知道为什么差这么多, 按理说 map 那个解法应该也是 linear 的才对;
Problem Description
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:
Special thanks to @ts for adding this problem and creating all test cases.
Difficulty:Easy
Category:Algorithms
Acceptance:46.19%
Contributor: LeetCode
Companies
adobe zenefits
Related Topics
array divide and conquer bit manipulation
Similar Questions
Majority Element II