给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。
找到所有出现两次的元素。
你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-duplicates-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
java:
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
for(int i=0; i<nums.length; i++){
int index = Math.abs(nums[i])-1;
nums[index] = -nums[index];
if(nums[index]>0){
res.add(index+1);
}
}
return res;
}
}
注意:
- 链表声明方式:List<Integer> res = new ArrayList<Integer>()
- 思路:当前访问的值存为索引信息,将该索引对应元素取反,这样即保持了数据信息,又记录了访问过哪些数据