442. Find All Duplicates in an Array - LeetCode
Posted okokabcd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了442. Find All Duplicates in an Array - LeetCode相关的知识,希望对你有一定的参考价值。
Question
442.?Find All Duplicates in an Array
Solution
题目大意:在数据中找重复两次的数
思路:数组排序,前一个与后一个相同的即为要找的数
Java实现:
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
if (nums.length == 0) return ans;
Arrays.sort(nums);
int last = nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] == last) {
ans.add(last);
}
last = nums[i];
}
return ans;
}
Ref
// when find a number i, flip the number at position i-1 to negative.
// if the number at position i-1 is already negative, i is the number that occurs twice.
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;
}
以上是关于442. Find All Duplicates in an Array - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章
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