File tree 3 files changed +99
-0
lines changed
lcci/17.10.Find Majority Element
3 files changed +99
-0
lines changed Original file line number Diff line number Diff line change @@ -184,6 +184,40 @@ public class Solution {
184
184
}
185
185
```
186
186
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
+
187
221
<!-- tabs: end -->
188
222
189
223
<!-- end -->
Original file line number Diff line number Diff line change @@ -177,6 +177,40 @@ public class Solution {
177
177
}
178
178
```
179
179
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
+
180
214
<!-- tabs: end -->
181
215
182
216
<!-- end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments