原题网址:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
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.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
方法:用循环检测方法。
public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
for(int i = 0; i < nums.length; i++) {
int n = nums[i];
nums[i] = -1;
while (n != -1 && nums[n - 1] != n) {
int t = nums[n - 1];
nums[n - 1] = n;
n = t;
}
}
List<Integer> result = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
if (nums[i] == -1) result.add(i + 1);
}
return result;
}
}
本文介绍了一种在不使用额外空间且时间复杂度为O(n)的情况下寻找数组中消失的整数的方法。通过循环检测,该算法能有效地找到指定范围内未出现在数组中的所有整数。

381

被折叠的 条评论
为什么被折叠?



