169. 多数元素

题目链接:https://leetcode-cn.com/problems/majority-element/

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

  • 输入:[3,2,3]
  • 输出:3

示例 2:

  • 输入:[2,2,1,1,1,2,2]
  • 输出:2

swift,在数组中计数

执行用时:104 ms, 在所有 Swift 提交中击败了96.19% 的用户
内存消耗:15.1 MB, 在所有 Swift 提交中击败了90.95% 的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
func majorityElement(_ nums: [Int]) -> Int {
if nums.count == 1 {
return nums[0]
}
let size = nums.count/2 + 1
var arr = [Int : Int]()
var res = 0
for i in nums {
if let value = arr[i] {
arr[i]! += 1
if arr[i]! >= size {
res = i
}
}else{
arr[i] = 1
}
}
return res
}
}

官方题解有证明过程,非常interesting

执行用时:1 ms, 在所有 Java 提交中击败了99.92% 的用户
内存消耗:44.3 MB, 在所有 Java 提交中击败了47.56% 的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int majorityElement(int[] nums) {
int count = 0, compare = 0;
for(int i : nums) {
if (count == 0) {
compare = i;
}
// 判断当前元素是否和比较中的元素相等,不相等则次数-1
count += i == compare ? 1 : -1;
}
return compare;
}
}

169. 多数元素
https://pisces34.github.io/2022/01/23/leetcode/169/
发布于
2022年1月23日
许可协议