Skip to content

Commit 968762b

Browse files
authored
feat: add swift implementation to lcci problem: No.17.10 (doocs#2782)
1 parent 8fbe73d commit 968762b

File tree

3 files changed

+99
-0
lines changed

3 files changed

+99
-0
lines changed

lcci/17.10.Find Majority Element/README.md

+34
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,40 @@ public class Solution {
184184
}
185185
```
186186

187+
```swift
188+
class Solution {
189+
func majorityElement(_ nums: [Int]) -> Int {
190+
var count = 0
191+
var candidate: Int?
192+
193+
for num in nums {
194+
if count == 0 {
195+
candidate = num
196+
count = 1
197+
} else if let candidate = candidate, candidate == num {
198+
count += 1
199+
} else {
200+
count -= 1
201+
}
202+
}
203+
204+
count = 0
205+
if let candidate = candidate {
206+
for num in nums {
207+
if num == candidate {
208+
count += 1
209+
}
210+
}
211+
if count > nums.count / 2 {
212+
return candidate
213+
}
214+
}
215+
216+
return -1
217+
}
218+
}
219+
```
220+
187221
<!-- tabs:end -->
188222

189223
<!-- end -->

lcci/17.10.Find Majority Element/README_EN.md

+34
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,40 @@ public class Solution {
177177
}
178178
```
179179

180+
```swift
181+
class Solution {
182+
func majorityElement(_ nums: [Int]) -> Int {
183+
var count = 0
184+
var candidate: Int?
185+
186+
for num in nums {
187+
if count == 0 {
188+
candidate = num
189+
count = 1
190+
} else if let candidate = candidate, candidate == num {
191+
count += 1
192+
} else {
193+
count -= 1
194+
}
195+
}
196+
197+
count = 0
198+
if let candidate = candidate {
199+
for num in nums {
200+
if num == candidate {
201+
count += 1
202+
}
203+
}
204+
if count > nums.count / 2 {
205+
return candidate
206+
}
207+
}
208+
209+
return -1
210+
}
211+
}
212+
```
213+
180214
<!-- tabs:end -->
181215

182216
<!-- end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
func majorityElement(_ nums: [Int]) -> Int {
3+
var count = 0
4+
var candidate: Int?
5+
6+
for num in nums {
7+
if count == 0 {
8+
candidate = num
9+
count = 1
10+
} else if let candidate = candidate, candidate == num {
11+
count += 1
12+
} else {
13+
count -= 1
14+
}
15+
}
16+
17+
count = 0
18+
if let candidate = candidate {
19+
for num in nums {
20+
if num == candidate {
21+
count += 1
22+
}
23+
}
24+
if count > nums.count / 2 {
25+
return candidate
26+
}
27+
}
28+
29+
return -1
30+
}
31+
}

0 commit comments

Comments
 (0)