1. 程式人生 > >LeetCode 442. Find All Duplicates in an Array (在數組中找到所有的重復項)

LeetCode 442. Find All Duplicates in an Array (在數組中找到所有的重復項)

nts ext leet 日期 lin dot 目標 input output

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]


題目標簽:Array   題目給了我們一個nums array,其中有一些數字出現兩次,剩下的都只出現一次,讓我們把重復兩次的都找出來。   因為這道題目沒有規定我們不能改動 array,所以可以把array 裏的 num 和 在 nums[ num - 1 ] 做一對一的映射,每次遇到一個num, 把對應位置上的 num 改成 -num 標記。如果遇到一個重復項,那麽肯定已經有同樣的數字來標記過了。

Java Solution:

Runtime beats 85.92%

完成日期:09/19/2017

關鍵詞:Array

關鍵點:把num 和 num[num - 1] 做1對1的映射

 1 class Solution 
 2 {
 3     public List<Integer> findDuplicates(int[] nums) 
 4     {
 5         List<Integer> duplicates = new ArrayList<>();
 6         
 7         for(int num: nums)
 8         {
 9             int
absNum = Math.abs(num); 10 11 if(nums[absNum - 1] < 0) // if the number at position num - 1 is already negative 12 duplicates.add(absNum); // num is duplicate 13 else 14 nums[absNum - 1] *= -1; 15 } 16 17 return
duplicates; 18 } 19 }

參考資料:

https://discuss.leetcode.com/topic/64735/java-simple-solution

LeetCode 題目列表 - LeetCode Questions List

LeetCode 442. Find All Duplicates in an Array (在數組中找到所有的重復項)