码迷,mamicode.com
首页 > 其他好文 > 详细

442. Find All Duplicates in an Array

时间:2020-01-24 12:08:31      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:color   could   oid   temp   ash   array   without   inpu   his   

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

 

技术图片
 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 }
View Code

 

442. Find All Duplicates in an Array

标签:color   could   oid   temp   ash   array   without   inpu   his   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!