题目
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
思路一
利用HashMap存储数组值及存在的次数。由于一个数组中有且仅有一个数字超过数组长度的一半,利用该特性不必遍历所有元素:
1、先判断该元素是否在哈希表中,存在,则将其数量+1;否认将其放入哈希表中,数量为1;
2、如果哈希表中该元素的数量已经大于数组长度的一半,则返回该值。
import java.util.HashMap;
public class MajorityElement {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
//根据题目可知,一个数组中有且仅有一个数字超过数组长度的一半
int len = nums.length / 2;
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
map.put(nums[i], map.get(nums[i])+1);
}else{
map.put(nums[i], 1);
}
if(map.get(nums[i]) > len) return nums[i];
}
return 0;//默认不存在
}
public static void main(String[] args){
MajorityElement test = new MajorityElement();
int[] arr = {1,2,3,2,2,2,5,4,2};
int result = test.majorityElement(arr);
System.out.println(result);
}
}
思路二
由于数字中一定存在一个数字出现的次数超过数组长度的一半,则将数组排序后,位于中间的数字一定是这个数字。
import java.util.Arrays;
public class MajorityElement {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
public static void main(String[] args){
MajorityElement test = new MajorityElement();
int[] arr = {1,2,3,2,2,2,5,4,2};
int result = test.majorityElement(arr);
System.out.println(result);
}
}
思路三
假设第一次出现的数字是众数,与之后的数字比较,如果相等,计数count++如果不相等,count–;当count == 0时,说明target不是众数,则令target为当前数字(即默认当前数字为众数)。
class Solution {
public int majorityElement(int[] nums) {
int target = nums[0];
if(nums.length == 1) return target;
int count = 1;
//一次遍历:重复次数最多的数字,其次数大于数组的一半,则在遍历过程中,遇到其他数字,其次数-1,则最后留下的一定是该数字
for(int i = 1; i < nums.length; i++){
if(target == nums[i]){
count++;
}else{
count--;
}
if(count == 0){
target = nums[i];
count++;
}
}
return target;
}
}