Leetcode 448(Java)

来源:互联网 发布:云安全软件下载 编辑:程序博客网 时间:2024/06/01 17:59

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]

出现过的元素以其为下标获取数组中的值并取反,在对应元素大于0的情况下我们才取反,这样没有出现过的元素为下标的元素依然为正,可以写出AC码:(注意,元素范围为1~n,而下标范围为0~n-1)

public class Solution {    public List<Integer> findDisappearedNumbers(int[] nums) {        List<Integer> result = new ArrayList<Integer>();        int index = 0;        for(int i=0;i<nums.length;i++){            index = Math.abs(nums[i])-1;            if(nums[index]>0){                nums[index]=-nums[index];            }        }        for(int j=0;j<nums.length;j++){            if(nums[j]>0){                result.add(j+1);            }        }        return result;    }}
0 0