mirror of https://github.com/doocs/leetcode.git
feat: add swift implementation to lcof problem: No.39 (#2920)
This commit is contained in:
parent
ebefc762f9
commit
14496937b6
|
|
@ -196,6 +196,27 @@ public class Solution {
|
|||
}
|
||||
```
|
||||
|
||||
#### Swift
|
||||
|
||||
```swift
|
||||
class Solution {
|
||||
func majorityElement(_ nums: [Int]) -> Int {
|
||||
var cnt = 0
|
||||
var m = 0
|
||||
|
||||
for v in nums {
|
||||
if cnt == 0 {
|
||||
m = v
|
||||
cnt = 1
|
||||
} else {
|
||||
cnt += (m == v ? 1 : -1)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<!-- tabs:end -->
|
||||
|
||||
<!-- solution:end -->
|
||||
|
|
|
|||
|
|
@ -0,0 +1,16 @@
|
|||
class Solution {
|
||||
func majorityElement(_ nums: [Int]) -> Int {
|
||||
var cnt = 0
|
||||
var m = 0
|
||||
|
||||
for v in nums {
|
||||
if cnt == 0 {
|
||||
m = v
|
||||
cnt = 1
|
||||
} else {
|
||||
cnt += (m == v ? 1 : -1)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue