Problem : https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
Because all numbers in the array is in the range [1, n]. If all numbers exist in the array, we can always swap the numbers to make nums[i] = i + 1.
So try to swap the number to its correct position. Then iterate the array to find the missing number which nums[i] != i + 1
class Solution {
fun findDisappearedNumbers(nums: IntArray): List<int> {
for (i in 0 until nums.size) {
while (nums[i] != i+1) {
if (nums[nums[i] - 1] == nums[i]) {
break
}
val tmp = nums[nums[i] - 1]
nums[nums[i] - 1] = nums[i]
nums[i] = tmp
}
}
val result = mutableListOf<int>()
for (i in 0 until nums.size) {
if (nums[i] != i + 1) {
result.add(i+1)
}
}
return result
}
}
No comments:
Post a Comment