Skip to content

Commit 1449693

Browse files
authored
feat: add swift implementation to lcof problem: No.39 (doocs#2920)
1 parent ebefc76 commit 1449693

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

lcof/面试题39. 数组中出现次数超过一半的数字/README.md

+21
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,27 @@ public class Solution {
196196
}
197197
```
198198

199+
#### Swift
200+
201+
```swift
202+
class Solution {
203+
func majorityElement(_ nums: [Int]) -> Int {
204+
var cnt = 0
205+
var m = 0
206+
207+
for v in nums {
208+
if cnt == 0 {
209+
m = v
210+
cnt = 1
211+
} else {
212+
cnt += (m == v ? 1 : -1)
213+
}
214+
}
215+
return m
216+
}
217+
}
218+
```
219+
199220
<!-- tabs:end -->
200221

201222
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
func majorityElement(_ nums: [Int]) -> Int {
3+
var cnt = 0
4+
var m = 0
5+
6+
for v in nums {
7+
if cnt == 0 {
8+
m = v
9+
cnt = 1
10+
} else {
11+
cnt += (m == v ? 1 : -1)
12+
}
13+
}
14+
return m
15+
}
16+
}

0 commit comments

Comments
 (0)