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

LeetCode-Find All Duplicates in an Array

一、Description

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

題目大意:

給定一個長度為n的陣列,陣列元素的取值在1-n,有些元素出現兩次,有些出現一次。不用額外的空間,並用O(n)的時間找出所有出現兩次的元素。

二、Analyzation

我們可以遍歷這個陣列,每遇到一個元素x,就看nums[x - 1]上的值是否大於0,若大於0,則讓該值置為相反數,反之則說明x是一個重複出現的數,則加入list中。

三、Accepted code

public List<Integer> findDuplicates(int[] nums) {
    List<Integer> list = new ArrayList<>();
    if(nums == null || nums.length == 0)
        return list;
    for(int i = 0;i < nums.length;i++){
        int index = Math.abs(nums[i]);
        if(nums[index - 1] > 0){
            nums[index - 1] = - nums[index - 1];
        }else{
            list.add(Math.abs(nums[i]));
        }
    }
    return list;
}