問題: 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.git
方法: n等於數組長度,同時數組中的元素都小於等於n(1 ≤ a[i] ≤ n),因此數組中的元素也能夠表明數組下標(a[i]-1),只要對數組中出現元素對應位置加n,則該位置元素必大於n,而沒有出現過的元素對應位置元素必小於等於n,經過這種方式就能夠找到沒有出現過的元素。github
具體實現:數組
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 ")
}
}
複製代碼
有問題隨時溝通bash