问题: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
方法: n等于数组长度,同时数组中的元素都小于等于n(1 ≤ a[i] ≤ n),所以数组中的元素也可以代表数组下标(a[i]-1),只要对数组中出现元素对应位置加n,则该位置元素必大于n,而没有出现过的元素对应位置元素必小于等于n,通过这种方式就可以找到没有出现过的元素。
具体实现:
class FindDisappearedNumbers {
fun findDisappearedNumbers(nums: IntArray): List<Int> {
val list = mutableListOf<Int>()
val n = nums.size
for (i in nums.indices) {
nums[(nums[i]-1) % n] += n
}
for (i in nums.indices) {
if (nums[i] <= n) {
list.add(i+1)
}
}
return list
}
}
fun main(args: Array<String>) {
val array = intArrayOf(4, 3, 2, 7, 8, 2, 3, 1)
val findDisappearedNumbers = FindDisappearedNumbers()
val result = findDisappearedNumbers.findDisappearedNumbers(array)
for (no in result) {
println("$no ")
}
}
复制代码
有问题随时沟通