Skip to content

Commit 2283a9e

Browse files
authored
feat: add swift implementation to lcci problem: No.17.19 (#2806)
1 parent a760faf commit 2283a9e

File tree

3 files changed

+105
-0
lines changed

3 files changed

+105
-0
lines changed

lcci/17.19.Missing Two/README.md

+36
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,42 @@ func missingTwo(nums []int) []int {
142142
}
143143
```
144144

145+
```swift
146+
class Solution {
147+
func missingTwo(_ nums: [Int]) -> [Int] {
148+
let n = nums.count + 2
149+
var xor = 0
150+
151+
for num in nums {
152+
xor ^= num
153+
}
154+
155+
for i in 1...n {
156+
xor ^= i
157+
}
158+
159+
let diff = xor & (-xor)
160+
161+
var a = 0
162+
163+
for num in nums {
164+
if (num & diff) != 0 {
165+
a ^= num
166+
}
167+
}
168+
169+
for i in 1...n {
170+
if (i & diff) != 0 {
171+
a ^= i
172+
}
173+
}
174+
175+
let b = xor ^ a
176+
return [a, b]
177+
}
178+
}
179+
```
180+
145181
<!-- tabs:end -->
146182

147183
<!-- end -->

lcci/17.19.Missing Two/README_EN.md

+36
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,42 @@ func missingTwo(nums []int) []int {
135135
}
136136
```
137137

138+
```swift
139+
class Solution {
140+
func missingTwo(_ nums: [Int]) -> [Int] {
141+
let n = nums.count + 2
142+
var xor = 0
143+
144+
for num in nums {
145+
xor ^= num
146+
}
147+
148+
for i in 1...n {
149+
xor ^= i
150+
}
151+
152+
let diff = xor & (-xor)
153+
154+
var a = 0
155+
156+
for num in nums {
157+
if (num & diff) != 0 {
158+
a ^= num
159+
}
160+
}
161+
162+
for i in 1...n {
163+
if (i & diff) != 0 {
164+
a ^= i
165+
}
166+
}
167+
168+
let b = xor ^ a
169+
return [a, b]
170+
}
171+
}
172+
```
173+
138174
<!-- tabs:end -->
139175

140176
<!-- end -->

lcci/17.19.Missing Two/Solution.swift

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
func missingTwo(_ nums: [Int]) -> [Int] {
3+
let n = nums.count + 2
4+
var xor = 0
5+
6+
for num in nums {
7+
xor ^= num
8+
}
9+
10+
for i in 1...n {
11+
xor ^= i
12+
}
13+
14+
let diff = xor & (-xor)
15+
16+
var a = 0
17+
18+
for num in nums {
19+
if (num & diff) != 0 {
20+
a ^= num
21+
}
22+
}
23+
24+
for i in 1...n {
25+
if (i & diff) != 0 {
26+
a ^= i
27+
}
28+
}
29+
30+
let b = xor ^ a
31+
return [a, b]
32+
}
33+
}

0 commit comments

Comments
 (0)