kt: add «2965. Find Missing and Repeated Values»
URL: https://leetcode.com/problems/find-missing-and-repeated-values/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
e147651e12
commit
0897005fdd
1 changed files with 21 additions and 0 deletions
21
kt/find-missing-and-repeated-values.kt
Normal file
21
kt/find-missing-and-repeated-values.kt
Normal file
|
@ -0,0 +1,21 @@
|
|||
class Solution {
|
||||
fun findMissingAndRepeatedValues(grid: Array<IntArray>): IntArray {
|
||||
val n = grid.size.toLong()
|
||||
val n2 = n.toLong() * n
|
||||
|
||||
val (sum, sumOfSquares) =
|
||||
grid.fold(0L to 0L) { acc, row ->
|
||||
row.fold(acc) { (sum, sumOfSquares), x ->
|
||||
sum + x to sumOfSquares + x * x
|
||||
}
|
||||
}
|
||||
|
||||
val sumDiff = sum - n2 * (n2 + 1) / 2
|
||||
val sqrDiff = sumOfSquares - n2 * (n2 + 1) * (2 * n2 + 1) / 6
|
||||
|
||||
val repeating = ((sqrDiff / sumDiff + sumDiff) / 2).toInt()
|
||||
val missing = ((sqrDiff / sumDiff - sumDiff) / 2).toInt()
|
||||
|
||||
return intArrayOf(repeating, missing)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue