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 {
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- 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
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}
You can’t perform that action at this time.
0 commit comments