Skip to content

Commit a01d94e

Browse files
authored
Create 0645-set-mismatch.kt
1 parent 7f4610a commit a01d94e

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Diff for: kotlin/0645-set-mismatch.kt

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// O(n) time and O(1) space
2+
class Solution {
3+
fun findErrorNums(nums: IntArray): IntArray {
4+
val n = nums.size
5+
6+
var x = 0
7+
var y = 0
8+
for (i in 1..n) {
9+
x += nums[i - 1] - i
10+
y += nums[i - 1] * nums[i - 1] - i * i
11+
}
12+
13+
var missing = (y - x * x) / (2 * x)
14+
var duplicate = missing + x
15+
16+
return intArrayOf(duplicate, missing)
17+
}
18+
}
19+
20+
// Inplace data manipulation O(n) time and O(1) space
21+
class Solution {
22+
fun findErrorNums(nums: IntArray): IntArray {
23+
val res = IntArray (2)
24+
25+
for (i in nums.indices) {
26+
val n = Math.abs(nums[i])
27+
nums[n - 1] = -1 * nums[n - 1]
28+
if (nums[n - 1] > 0)
29+
res[0] = n
30+
}
31+
32+
for ((i, n) in nums.withIndex()) {
33+
if (n > 0 && i + 1 != res[0]) {
34+
res[1] = i + 1
35+
break
36+
}
37+
}
38+
39+
return res
40+
}
41+
}
42+
43+
// HashMap O(n) time and O(n) space
44+
class Solution {
45+
fun findErrorNums(nums: IntArray): IntArray {
46+
val res = IntArray (2)
47+
val counts = nums
48+
.asList()
49+
.groupingBy { it }
50+
.eachCount()
51+
52+
for (num in 1..nums.size) {
53+
val count = counts[num] ?: 0
54+
if (count == 0)
55+
res[1] = num
56+
if (count == 2)
57+
res[0] = num
58+
}
59+
60+
return res
61+
}
62+
}
63+
64+
// Use XOR O(n) time and O(1) space
65+
class Solution {
66+
fun findErrorNums(nums: IntArray): IntArray {
67+
val res = IntArray (2)
68+
69+
for (i in nums.indices) {
70+
val num = Math.abs(nums[i])
71+
72+
res[1] = res[1] xor ((i + 1) xor num)
73+
74+
if (nums[num - 1] < 0) res[0] = num
75+
else nums[num - 1] *= -1
76+
}
77+
78+
res[1] = res[1] xor res[0]
79+
return res
80+
}
81+
}

0 commit comments

Comments
 (0)