当前位置:网站首页>剑指 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)
边栏推荐
- Stack acwing 3302. Expression evaluation
- Inclusion exclusion principle acwing 890. divisible numbers
- VSCode复制代码时去掉样式/语法高亮/代码高亮/黑色背景
- Smart pointer (shared_ptr, unique_ptr, weak_ptr)
- 博弈论 AcWing 891. Nim游戏
- Everything cannot be searched for startup_ Lpc11x.s file
- The C programming language-2nd-- notes -- 4.11.3
- Knapsack model acwing 1024. Packing problem
- Installation and use of GTEST and gmock
- Game theory acwing 893. Set Nim game
猜你喜欢

WGet warning: unable to verify

箱型图介绍

容斥原理 AcWing 890. 能被整除的数

Gaussian elimination acwing 884. Gaussian elimination for solving XOR linear equations

Longest ascending subsequence model acwing 272. longest common ascending subsequence

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

82. (cesium home) cesium points move on 3D models

Moveit2 -- 2. Quick start of moveit in rviz

49 letter ectopic grouping and 242 effective letter ectopic words

第7章 异常处理
随机推荐
容斥原理 AcWing 890. 能被整除的数
Luogu p3052 [usaco12mar]cows in a skyscraper G
The longest ascending subsequence model acwing 1016. The sum of the largest ascending subsequence
Find the combination number acwing 885. find the combination number I
Tensorflow tensor operation function set
Error encountered in adding quick open option to right-click menu:
Digital triangle model acwing 1027. Grid retrieval
2022 Niuke multi school training (3) a-ancestor topic translation
LAN SDN hard core technology insider 24 outlook for the future - RDMA (middle)
LAN SDN hard core technology insider 23 looking forward to the future - RDMA (Part 1)
Inclusion exclusion principle acwing 890. divisible numbers
Smart pointer (shared_ptr, unique_ptr, weak_ptr)
博弈论 AcWing 893. 集合-Nim游戏
Several banks adjusted the redemption rules of cash management financial products: the confirmation time limit of redemption changed from "t+0" to "t+1"
Gaussian elimination acwing 884. Gaussian elimination for solving XOR linear equations
Error while unzipping file in win10: unable to create symbolic link. You may need to run WinRAR with administrator privileges. The client does not have the required privileges
(5) Printf (instead of echo)
为什么选择智能电视?
The C programming language -- (2nd) -- Notes -- 4.11.2
Quantitative industry knowledge summary