442. Find All Duplicates in an Array
Posted hyxsolitude
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 class Solution { 2 public List<Integer> findDuplicates(int[] nums) { 3 Set<Integer> set = new HashSet<>(); 4 List<Integer> ans = new ArrayList<>(); 5 int n = nums.length; 6 for (int i = 0; i < n; ++i) { 7 if (set.contains(nums[i])) { 8 ans.add(nums[i]); 9 10 } else { 11 set.add(nums[i]); 12 } 13 } 14 return ans; 15 } 16 }
1 class Solution { 2 public void swap(int []nums, int i, int j) { 3 int temp = nums[i]; 4 nums[i] = nums[j]; 5 nums[j] = temp; 6 } 7 public List<Integer> findDuplicates(int[] nums) { 8 9 List<Integer> ans = new ArrayList<>(); 10 int n = nums.length; 11 int i = 0; 12 while (i < n) { 13 if (nums[i] != nums[nums[i] - 1]) { 14 swap(nums, i, nums[i] - 1); 15 } else { 16 i++; 17 } 18 } 19 20 for (i = 0; i < n; ++i) { 21 if (i != nums[i] - 1) { 22 ans.add(nums[i]); 23 } 24 } 25 return ans; 26 } 27 }
以上是关于442. Find All Duplicates in an Array的主要内容,如果未能解决你的问题,请参考以下文章
442. Find All Duplicates in an Array
442. Find All Duplicates in an Array
442. Find All Duplicates in an Array
442. Find All Duplicates in an Array