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]
題目分析:拿着題目你或許會覺得奇怪?這個條件是幹啥的?1 ≤ a[i] ≤ n (n = size of array)????
是不是覺得這個條件沒什麼用?
但是!!!到最後我才發現這個題目的這個條件非常的重要,如果沒有這個條件那麼就很難在O(N)的時間複雜讀內解決這個問題。
題目解決辦法分析:
你會發現所有元素的大小一定是在數組的長度範圍內,那麼我們可以進行如下的操作:
來看一種正負替換的方法,這類問題的核心是就是找nums[i]和nums[nums[i] - 1]的關係,我們的做法是,對於每個nums[i],我們將其對應的nums[nums[i] - 1]取相反數,如果其已經是負數了,說明之前存在過,我們將其加入結果res中即可,參見代碼如下:[4,3,2,7,8,2,3,1]
比如這裏這個數組 執行順序如下

            //nums[3] = -7;
            //index = 2
            //nums[2] = -2
            //index = 1 
            //nums[1] = -3
            //index = 6
            //nums[6] = -2
            //index = 7
            //nums[7] = -3
            //index = 1
            //現在 發現nums[1] = -3 < 0 說明這個數字存在過2加入
            //index = 2
            //現在 發現nums[2] = -2 < 0 說明這個數字存在過3加入
            //index = 0
            //nums[0] = 4

Java代碼如下:

public static List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章