题目链接:https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/
分析:
题目中给出条件 1<= a[i] <=n(数组长度) 相当于 0<= a[i]-1 <= n-1,即数组中每个元素的值减去1以后的结果在数组下标的范围之内 ,我们可以用这个结果去判断是否出现了相同元素
程序:
class Solution442 {
public List<Integer> findDuplicates(int[] nums) {
//定义一个一位数组,用来存储出现两次的元素
List<Integer> res = new ArrayList<>();
if(nums.length == 0){
return res;
}
/**
题目中给出条件 1<= a[i] <=n(数组长度) 相当于 0<= a[i]-1 <= n-1
即数组中每个元素的值减去1以后的结果在数组下标的范围之内
我们可以用这个结果去判断是否出现了相同元素
*/
for(int i=0;i<nums.length;i++){
//数组中的值在转换之后又可能为负,所以在这里取其绝对值,然后再减1
int idx = Math.abs(nums[i])-1;
if(nums[idx] > 0){
//如果这个数为正,那么让这个数乘以负1
nums[idx] *= -1;
}else{
//如果这个数为负,说明当前的idx值在之前出现过一次,即对应的数出现了两次
res.add(idx+1);
}
}
return res;
}
}