当前位置:网站首页>剑指 Offer 笔记: T39. 数组中出现次数超过一半的数字
剑指 Offer 笔记: T39. 数组中出现次数超过一半的数字
2022-07-27 10:58:00 【无知小九】
T39. 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
思路
用二分的手法, 最后中间的数就是这个数字
解法 1 直接排序
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length>>1];
}
}
执行用时:2 ms, 在所有 Java 提交中击败了**60.35%**的用户
内存消耗:43.9 MB, 在所有 Java 提交中击败了**9.12%**的用户
解法 2 摩尔投票(巧妙)
class Solution {
public int majorityElement(int[] nums) {
int n=0, count=0;
for(int num:nums){
if(count==0){
n = num;
}
if(num ==n){
count++;
}else count--;
}
return n;
}
}
执行用时:1 ms, 在所有 Java 提交中击败了**99.97%**的用户
内存消耗:41.5 MB, 在所有 Java 提交中击败了**87.71%**的用户
时间复杂度:O(n),空间复杂度:O(1)
边栏推荐
- 什么是私域流量?
- LeetCode 03: T58. 最后一个单词的长度(简单); 剑指 Offer 05. 替换空格(简单); 剑指 Offer 58 - II. 左旋转字符串(简单)
- State compression DP acwing 91. shortest Hamilton path
- (8) Shell function
- The longest ascending subsequence model acwing 1016. The sum of the largest ascending subsequence
- 背包问题 AcWing 9. 分组背包问题
- Longest ascending subsequence model acwing 1014. mountaineering
- origin如何作一张图中多张子图是柱状图(或其他图)
- 求组合数 AcWing 889. 满足条件的01序列
- 博弈论 AcWing 891. Nim游戏
猜你喜欢

博弈论 AcWing 891. Nim游戏

背包问题 AcWing 9. 分组背包问题

数字三角形模型 AcWing 1027. 方格取数

Modelarts voice detection and text classification

Find the combination number acwing 885. find the combination number I

数字三角形模型 AcWing 1018. 最低通行费

Caused by:org.gradle.api.internal. plugins . PluginApplicationException: Failed to apply plugin

origin如何作一张图中多张子图是柱状图(或其他图)

Longest ascending subsequence model acwing 1014. mountaineering

makefile模板
随机推荐
Error encountered in adding quick open option to right-click menu:
Stack acwing 3302. Expression evaluation
LeetCode 02: 剑指 Offer 58 - I. 翻转单词顺序(简单); T123. 验证回文串 ; T9. 回文数
剑指 Offer 笔记: T53 - I. 在排序数组中查找数字
C# 自定义集合
第10章 枚举类与注解
Find the combination number acwing 886. find the combination number II
博弈论 AcWing 891. Nim游戏
Local virtual machine initialization script
Kepserver configuration
Caused by:org.gradle.api.internal. plugins . PluginApplicationException: Failed to apply plugin
Chinese remainder theorem acwing 204. strange way of expressing integers
剑指 Offer 笔记: T57 - I. 和为 s 的两个数字
Modelarts voice detection and text classification
LAN SDN technology hard core insider 12 cloud CP's daily love - hardware vxlan forwarding plane
局域网SDN技术硬核内幕 13 从局域网到互联网
为什么TCP三次握手的时候ACK=Seq+1
C programming language (2nd Edition) -- Reading Notes -- 1.5.2
C programming language (2nd Edition) -- Reading Notes -- 1.5.3
(4) Operator