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.
给定一个长度为n的数组,找出最多的元素。最多的元素指的是出现次数超过n/2次的元素。假定数组非空并且这个元素始终存在。
这个题目解法很多。
方法一:对数组进行排序,处于索引n/2处的元素出现的次数必定且唯一超过了n/2次。
这里用了java中Arrays.sort排序方法,Arrays.sort有快速排序和优化的合并排序两种排序算法。快速排序主要是对基本类型数据(int,short,long等)排序;合并排序用于对引用类型进行排序。时间复杂度均为n*logn。
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
leetcode的推荐算法: