File tree Expand file tree Collapse file tree 1 file changed +10
-16
lines changed Expand file tree Collapse file tree 1 file changed +10
-16
lines changed Original file line number Diff line number Diff line change @@ -3,32 +3,26 @@ class Solution {
3
3
// Solution by Sergey Leschev
4
4
// 2965. Find Missing and Repeated Values
5
5
6
- // HashMap
6
+ // Math
7
7
// Time complexity: O(n * n)
8
- // Space complexity: O(n * n )
8
+ // Space complexity: O(1 )
9
9
10
10
func findMissingAndRepeatedValues( _ grid: [ [ Int ] ] ) -> [ Int ] {
11
- var freq = [ Int: Int] ( )
12
11
let n = grid. count
12
+ let N = n * n
13
+ var sum = 0
14
+ var sqrSum = 0
13
15
14
16
for i in 0 ..< n {
15
17
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]
17
20
}
18
21
}
19
22
20
- var repeated = 0
21
- var missing = 0
23
+ let c1 = sum - N * ( N + 1 ) / 2
24
+ let c2 = sqrSum - N * ( N + 1 ) * ( 2 * N + 1 ) / 6
22
25
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 ]
33
27
}
34
28
}
You can’t perform that action at this time.
0 commit comments