LeetCode 442. 数组中重复的数据(Find All Duplicates in an Array) 17

时间:2023-03-10 01:02:12
LeetCode 442. 数组中重复的数据(Find All Duplicates in an Array) 17

442. 数组中重复的数据

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?

给定一个整数数组 a,其中 1 ≤ a[i] ≤ n(n 为数组长度),其中有些元素出现两次而其他元素出现一次

找到所有出现两次的元素。

你可以不用到任何额外空间并在 O(n) 时间复杂度内解决这个问题吗?

每日一算法2019/5/20Day 17LeetCode442. Find All Duplicates in an Array

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:

[2,3]

Java 实现

import java.util.ArrayList;
import java.util.List; class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) {
res.add(Math.abs(index + 1));
}
nums[index] = -nums[index];
}
return res;
}
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set; class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; ++i) {
if (!set.add(nums[i])) {
res.add(nums[i]);
}
}
return res;
}
}

相似题目

参考资料