LeetCode 442. Find All Duplicates in an Array (在数组中找到所有的重复项)
Posted 几米空间
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]
Java Solution:
Runtime beats 85.92%
完成日期:09/19/2017
关键词:Array
关键点:把num 和 nums[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 (在数组中找到所有的重复项)的主要内容,如果未能解决你的问题,请参考以下文章
442. Find All Duplicates in an Array(LeetCode)
LeetCode - 442. Find All Duplicates in an Array
442. Find All Duplicates in an Array - LeetCode
LeetCode解题思路:442. Find All Duplicates in an Array
LeetCode 442. Find All Duplicates in an Array
LeetCode 448. Find All Numbers Disappeared in an Array & 442. Find All Duplicates in an Array(示例