【一次过】Lintcode 1236. Find All Numbers Disappeared in an Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82862287

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.

样例

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]


解题思路1:

很自然的想到用HashSet存储,然后在区间元素寻找是否在其中即可。时间O(n),空间O(n)。

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: return a list of integers
     */
    public List<Integer> findDisappearedNumbers(int[] nums) {
        // write your code here
        List<Integer> list = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        
        for(int num : nums)
            set.add(num);
        
        for(int i=1 ; i<=nums.length ; i++){
            if(!set.contains(i))
                list.add(i);
        }
        
        return list;
    }
}

解题思路2:

由于题目要求不能有额外空间,所以

标志位法:用正负标志位,区分出现的元素和未出现的元素

从左向右遍历数组arr,假设当前遍历到 arr 的第 i 个元素,用一个变量 j 记录 | arr[i] | - 1,访问arr 的第 j 个元素,如果该元素为正,则把它变为负;否则不变。

最后,遍历一遍数组,如果某个位置上的元素为正,说明该位置从来没有被访问过。

图中,arr[4] 和 arr[5]上的值为正,表示5(5 = 4 +1)、6(6 = 5+1)从未在arr中出现过。

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: return a list of integers
     */
    public List<Integer> findDisappearedNumbers(int[] nums) {
        // write your code here
        List<Integer> res = new ArrayList<Integer>();
        
        for(int i = 0; i < nums.length; i++) {
            int val = Math.abs(nums[i]) - 1;
            if(nums[val] > 0)
                nums[val] = -nums[val];
        }
        
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] > 0)
                res.add(i+1);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82862287