[LeetCode] 442. Find All Duplicates in an Array

【原題】
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?

Example:

Input:

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

Output:

[2,3]

【解釋】
給定一個含有那個元素的數組, 數組中的元素要麼出現一次要麼出現兩次,要求找出數組中所有的重複元素。
【思路】
因爲數組元素的取值都不會越界,且數組只有出現一次和兩次良好總可能性,那麼可以把書組元素當成是數組的index。循環每次index-1的數乘上-1,若該index-1元素已經爲負數,則說明該index之前已經出現過,故必爲重複元素,將其加到list即可。

因爲這裏最多出現兩次,所以不需要判斷要加入的元素是否會存在list中,剛開始博主就是這樣的思想,判斷會增加時間複雜度,最終最後一個測試用例不通過,會後換成hashset,再轉成list才通過[捂臉]。

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> list=new ArrayList<Integer>();
        //HashSet<Integer> hashSet=new HashSet<>();
        for(int i=0;i<nums.length;i++){
            int index=Math.abs(nums[i]);
            if(nums[index-1]<0) //若該index已經爲負數,說明前面已經出現過,則這個index肯定是重複的元素
                 list.add(index);
            nums[index-1]*=-1;
        }
        return list;

    }
}
發佈了56 篇原創文章 · 獲贊 103 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章