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]
Solutions:
class Solution {
//Input:[4,3,2,7,8,2,3,1]
//index:[3,2,1,6,7,1,2,0] -> index对应nums中的值变为负数
//index的值判断是否为负即可知道是否重复
//时间复杂度O(n)
public List<Integer> findDuplicates(int[] nums) {
List<Integer> list = new ArrayList<>();
for(int i=0;i<nums.length;i++){
int index = Math.abs(nums[i])-1;
if(nums[index]<0)
list.add(index+1);
nums[index] = -nums[index];
}
return list;
}
}
本文介绍了一种在不使用额外空间且时间复杂度为O(n)的情况下寻找数组中重复元素的方法。通过将数组下标作为索引,并利用数值的正负标志来标记已访问状态,有效地找出所有重复出现的元素。
385

被折叠的 条评论
为什么被折叠?



