Java实现 LeetCode 448 找到全部数组中消失的数字

448. 找到全部数组中消失的数字

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另外一些只出现一次。java

找到全部在 [1, n] 范围之间没有出如今数组中的数字。数组

您能在不使用额外空间且时间复杂度为O(n)的状况下完成这个任务吗? 你能够假定返回的数组不算在额外空间内。app

示例:ide

输入:
[4,3,2,7,8,2,3,1]code

输出:
[5,6]
经过次数29,638提交次数51,956it

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> results = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[Math.abs(nums[i]) - 1] > 0) {
                nums[Math.abs(nums[i]) - 1] = - nums[Math.abs(nums[i]) - 1];
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                results.add(i + 1);
            }
        }
        return results;
    }
}
相关文章
相关标签/搜索