Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a379bad

Browse files
2965. Find Missing and Repeated Values
1 parent 679c342 commit a379bad

File tree

1 file changed

+10
-16
lines changed

1 file changed

+10
-16
lines changed

‎2501-3000/2965. Find Missing and Repeated Values.swift

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,26 @@ class Solution {
33
// Solution by Sergey Leschev
44
// 2965. Find Missing and Repeated Values
55

6-
// HashMap
6+
// Math
77
// Time complexity: O(n * n)
8-
// Space complexity: O(n * n)
8+
// Space complexity: O(1)
99

1010
func findMissingAndRepeatedValues(_ grid: [[Int]]) -> [Int] {
11-
var freq = [Int: Int]()
1211
let n = grid.count
12+
let N = n * n
13+
var sum = 0
14+
var sqrSum = 0
1315

1416
for i in 0..<n {
1517
for j in 0..<n {
16-
freq[grid[i][j], default: 0] += 1
18+
sum += grid[i][j]
19+
sqrSum += grid[i][j] * grid[i][j]
1720
}
1821
}
1922

20-
varrepeated = 0
21-
varmissing = 0
23+
letc1 = sum - N *(N +1)/2
24+
letc2 = sqrSum - N *(N +1)*(2* N +1)/6
2225

23-
for i in 1...(n * n) {
24-
if freq[i] == 2 {
25-
repeated = i
26-
}
27-
if freq[i] == nil {
28-
missing = i
29-
}
30-
}
31-
32-
return [repeated, missing]
26+
return [(c2 / c1 + c1) / 2, (c2 / c1 - c1) / 2]
3327
}
3428
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /