题目
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
解法一
思路
看到这个题,直接想到用hashmap来存<数字,出现次数>这样的键值对,遍历一遍数组,当存完后,遍历一遍hashmap,找出value>n/2对应的key即可。
代码
class Solution {
public int majorityElement(int[] nums) {
int res = -1;
Map<Integer,Integer> count = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
count.put(nums[i], count.getOrDefault(nums[i],0)+1);
}
for(int num : nums){
if(count.get(num)>nums.length/2){
res = num;
break;
}
}
return res;
}
}
解法二
思路
直接对数组进行排序,然后直接返回第n/2个元素即可(因为这个题的案例是保证存在的,所以这样绝对可以找到)
代码
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return (nums[nums.length/2]);
}
}
解法三
思路
直接对数组的每个元素的每一位进行遍历(用两个for循环),因为我们要找数组中出现频次大于n/2的数字,所以对于32中的任何一位,总会有0或1超过一半的情形,所以我们统计每一位上0或1的频次,频次较高的就是res这一位上的数组。很巧妙~~
代码
class Solution {
public int majorityElement(int[] nums) {
int res = 0;
int n = nums.length;
for(int i = 0; i < 32; i++) {
int ones = 0, zeroes = 0;
for(int num : nums) {
if(ones > n/2 || zeroes > n/2) break;
if((num & (1 << i)) != 0) ones++;
else zeroes++;
}
if(ones > zeroes) res |= (1 << i);
}
return res;
}
}
解法四
思路
求一个频次超过n/2的数,我们可以设置一个计数器,指向第一个数字,将第一个数字设为res,并将计数器初始为1,如果下一个数字与该数字相同,则加1,不同则减1;如果到某个数字,计数器为0,则将该数字设为res。原理:如果到某个数字计数器为0,则相当于在整个数组中删去了相同数量的众数与非众数,那么数组中剩下的数字中众数仍然过半,仍能找到它。
代码
class Solution {
public int majorityElement(int[] nums) {
int res = 0;
int cnt = 0;
for(int num:nums) {
if(cnt == 0) {res = num; cnt++;}
else if(num == res) cnt++;
else cnt--;
}
return res;
}
}