169. Majority Element
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.
思路:由于给定数组一定存在Majority Element,所以比较做法比较简单,最直接的做法是:排序(O(nlogn),中间的那个一定是Majority Element,还有一种效率更好,时间复杂度只有O(n).
public class Solution {
public int majorityElement(int[] nums) {
// 方法一:排序
// Arrays.sort(nums);
// int len = nums.length;
// return nums[len/2];
// 方法二:遍历
int majorityE=nums[0];
int count=1;//将majorityElement初始设为第一个元素,计数为1
for(int i=1;i<nums.length;i++){
if(nums[i]==majorityE){
count++;
}else if(count==0){
majorityE=nums[i];
count++;
}else{
count--;
}
}
return majorityE;
}
}