442. Find All Duplicates in an Array

时间:2020-01-24 11:11:13   收藏:0   阅读:99

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 }
View Code

 

原文:https://www.cnblogs.com/hyxsolitude/p/12231947.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!