当前位置:网站首页>LeetCode 进阶之路 - 169.多数元素
LeetCode 进阶之路 - 169.多数元素
2022-06-10 20:00:00 【Li_XiaoJin】
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
题解里说得比较通俗易懂的。https://leetcode-cn.com/problems/majority-element/solution/3chong-fang-fa-by-gfu-2/
- 排序法 既然数组中有出现次数> ⌊ n/2 ⌋的元素,那排好序之后的数组中,相同元素总是相邻的。 即存在长度> ⌊ n/2 ⌋的一长串 由相同元素构成的连续子数组。
- 遍历法(哈希表) 遍历整个数组,对记录每个数值出现的次数(利用HashMap,其中key为数值,value为出现次数); 接着遍历HashMap中的每个Entry,寻找value值> nums.length / 2的key即可。
- 摩尔投票法 候选人(cand_num)初始化为nums[0],票数count初始化为1。 当遇到与cand_num相同的数,则票数count = count + 1,否则票数count = count - 1。 当票数count为0时,更换候选人,并将票数count重置为1。 遍历完数组后,cand_num即为最终答案。 为何这行得通呢? 投票法是遇到相同的则票数 + 1,遇到不同的则票数 - 1。 且“多数元素”的个数> ⌊ n/2 ⌋,其余元素的个数总和<= ⌊ n/2 ⌋。 因此“多数元素”的个数 - 其余元素的个数总和 的结果 肯定 >= 1。 这就相当于每个“多数元素”和其他元素 两两相互抵消,抵消到最后肯定还剩余至少1个“多数元素”。 无论数组是1 2 1 2 1,亦或是1 2 2 1 1,总能得到正确的候选人。
public class MajorityElement {
/**
* 排序法
* @param nums
* @return
*/
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
/**
* 遍历法(哈希表)
* @param nums
* @return
*/
public int majorityElement1(int[] nums) {
int n = nums.length >> 1;
Map<Integer, Integer> map = new HashMap(nums.length);
for (int i = 0; i < nums.length; i++) {
int temp = map.get(nums[i]) == null ? 0 : map.get(nums[i]);
if (temp != 0) {
++temp;
if (temp > n) {
return nums[i];
}
map.put(nums[i], temp);
} else {
map.put(nums[i], 1);
}
}
return nums[0];
}
/**
* 摩尔投票法
* @param nums
* @return
*/
public int majorityElement2(int[] nums) {
int can_num = nums[0],count = 1;
for (int i = 1; i < nums.length; i++) {
if (can_num == nums[i]) {
++count;
} else if (--count == 0) {
can_num = nums[i];
count = 1;
}
}
return can_num;
}
public static void main(String[] args) {
// int[] nums = new int[]{1};
// int[] nums = new int[]{3,2,3};
int[] nums = new int[]{2,2,1,1,1,2,2};
MajorityElement majorityElement = new MajorityElement();
System.out.println(majorityElement.majorityElement2(nums));
}
}
Copyright: 采用 知识共享署名4.0 国际许可协议进行许可 Links:https://lixj.fun/archives/leetcode进阶之路-169多数元素
边栏推荐
- Redis缓存穿透
- MySQL - common functions
- 蛮力法/任务分配
- LeetCode:1037. Effective boomerang - simple
- 六级考试-商务英语-考前最后一背
- 中衍期货公司是国内的正规平台吗?开户安全吗?想开个期货账户
- Meetup预告:Linkis新版本介绍以及DSS的应用实践
- 【电脑使用】如何设置没有自启项的软件开机启动
- 堆排序与加强堆代码 用于记忆
- The new audio infinix machine appears in the Google product library, and Tecno CaMon 19 is pre installed with Android 13
猜你喜欢

canvas 高级功能(中)

35岁被裁员,还能拥有美妙人生吗?

中国工科研究生200多篇英文论文中最常见的习惯(The Most Common Habits from more than 200 English Papers written by Gradua)

An old programmer of about 10 years said: simple crud function enters the era of codeless development 1. Adding, deleting, modifying and checking interface information

Jiangbolong forestee xp2000 PCIe 4.0 SSD multi encryption function, locking data security

pytorch深度学习——卷积操作以及代码示例

What is the difference between localhost and 127.0.0.1?

Finally, someone explained the difference among cookies, sessions and tokens. Detailed explanation, interview questions.

JD released ted-q, a large-scale and distributed quantum machine learning platform based on tensor network acceleration

Deploying static websites using OSS and CDN on Alibaba cloud international
随机推荐
JS basic and frequently asked interview questions [] = =! [] result is true, [] = = [] result is false detailed explanation
Build a BPMN modeling Web Service
synergy: server refused client with our name
Is Zhongyan futures reliable? Is it a regular futures company? Is it safe to open an account?
vulnhub-The Planets: Earth
Elastic-Job的快速入门,三分钟带你体验分布式定时任务
H5 van-popup全屏弹窗,模拟页面回退效果,支持左上角返回按钮,适用物理返回,侧滑与底部返回键
js基础及常考面试题之 [] == ![]结果为true, []==[]结果为false 详解
Why do some web page style attributes need a colon ":" and some do not?
Codeforces Round #798 (Div. 2)
Canvas advanced functions (Part 1)
获取的网络时间 + 时区(+8)
Recommend a crud tool that may become the best crud tool in 2019 during the National Day
Arduino中Serial.print()与Serial.write()函数的区别,以及串口通信中十六进制与字符串的收发格式问题和转换过程详解
2台电脑共享一套键盘鼠标
聊聊服务器性能优化~(建议收藏)
The excess part of the table setting is hidden. Move the mouse to display all
Canvas advanced functions (medium)
编程式导航路由跳转到当前路由(参数不变), 多次执行会抛出NavigationDuplicated的警告错误?
synergy: server refused client with our name