[LeetCode][Python]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.1 Python中有個collections模塊,它提供了個類Counter,用來跟蹤值出現了多少次。注意key的出現順序是根據計數的從大到小。它的一個方法most_common(n)返回一個list, list中包含Counter對象中出現最多前n個元素。

1.2 heapq模塊有兩個函數:nlargest() 和 nsmallest() 可以從一個集合中獲取最大或最小的N個元素列表。heapq.nlargest (n, heap) #查詢堆中的最大元素,n表示查詢元素個數

1.3 使用字典,依次查看數組中的元素,如果在字典中,則放入另外用來統計的list

class Solution(object):
    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        return [no for no, count in collections.Counter(nums).items() if count > 1]

Java思路:(我還沒想明白:()
// 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.
//The concept here is to negate each number's index as the input is 1 <= a[i] <= n (n = size of array).
// Once a value is negated, if it requires to be negated again then it is a duplicate.

    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;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容