442. Find All Duplicates in an Array

Question

442. Find All Duplicates in an Array

Solution

题目大意:在数据中找重复两次的数

思路:数组排序,前一个与后一个相同的即为要找的数

Java实现:

public List<Integer> findDuplicates(int[] nums) {
    List<Integer> ans = new ArrayList<>();
    if (nums.length == 0) return ans;
    Arrays.sort(nums);
    int last = nums[0];
    for (int i=1; i<nums.length; i++) {
        if (nums[i] == last) {
            ans.add(last);
        }
        last = nums[i];
    }
    return ans;
}

Ref

// when find a number i, flip the number at position i-1 to negative. 
// if the number at position i-1 is already negative, i is the number that occurs twice.

public List<Integer> findDuplicates(int[] nums) {
    List<Integer> res = new ArrayList<>();
    for (int i = 0; i < nums.length; ++i) {
        int index = Math.abs(nums[i])-1;
        if (nums[index] < 0)
            res.add(Math.abs(index+1));
        nums[index] = -nums[index];
    }
    return res;
}
原文地址:https://www.cnblogs.com/okokabcd/p/9398476.html