方法1:
投票法:
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer tempTarget = null;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
tempTarget = nums[i];
count++;
} else {
if (nums[i] != tempTarget) {
count--;
} else count++;
}
}
return tempTarget;
}
}
方法2:
map法(Hash法)
//给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
//
// 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
//
//
//
// 示例 1:
//
//
//输入:nums = [3,2,3]
//输出:3
//
// 示例 2:
//
//
//输入:nums = [2,2,1,1,1,2,2]
//输出:2
//
//
//
//提示:
//
//
// n == nums.length
// 1 <= n <= 5 * 10⁴
// -10⁹ <= nums[i] <= 10⁹
//
//
//
//
// 进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
//
// Related Topics 数组 哈希表 分治 计数 排序 👍 2136 👎 0
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> tempMap=new HashMap<>();
for (int i = 0; i < nums.length; i++) {
// if(tempMap.get(nums[i])!=null){
// tempMap.put(nums[i],tempMap.get(nums[i])+1);
// }else {
// tempMap.put(nums[i],1);
// }
tempMap.compute(nums[i], (key, val) -> {
return (val == null) ? 1 : val + 1;
});
}
Map.Entry<Integer,Integer> compareEntry=null;
for(Map.Entry<Integer,Integer> entry:tempMap.entrySet()){
if(compareEntry==null||entry.getValue()>compareEntry.getValue()){
compareEntry=entry;
}
}
return compareEntry.getKey();
}
}
//leetcode submit region end(Prohibit modification and deletion)