1. 程式人生 > >442. Find All Duplicates in an Array - LeetCode

442. Find All Duplicates in an Array - LeetCode

一個 length problem array pre ber http arrays 相同

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;
}

442. Find All Duplicates in an Array - LeetCode