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

LeetCode 442. Find All Duplicates in an Array

Problem Statement

(Source) 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]

Solution

關鍵點: 1 ≤ a[i] ≤ n (n = size of array)。根據這點資訊,可以想象: 從左向右掃描該資料時,對於每一個當前位置,把能成功(目標位置當前元素沒有滿足condition)放到目標位置(condition: index == arr[index] - 1) 的當前位置元素和目標位置的元素交換,直到不能交換為止,繼續向前掃描。當上述掃描過程完畢時,再從前往後掃描一次該陣列,不滿足condition的位置的元素皆為目標duplicates。演算法的時間複雜度為O(n),雖有兩次掃描陣列的過程,第一次掃描中的交換過程最多執行n次,掃描總時間複雜度為O

(n);第二次掃描時間也是O(n)。所以總共的時間複雜度為O(n)。演算法沒有使用extra space,符合要求。

class Solution(object):
    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums or len(nums) < 2:
            return []

        i, n = 0, len(nums)
        for
i in xrange(n): while nums[i] != i + 1: if nums[nums[i] - 1] == nums[i]: break j = nums[i] - 1 nums[i], nums[j] = nums[j], nums[i] # Wrong swap below: # nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i] return [nums[i] for i in xrange(n) if nums[i] != i + 1]

[TODO]: What is “extra space”?