一、Description
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?
题目大意:
给定一个长度为n的数组,数组元素的取值在1-n,有些元素出现两次,有些出现一次。不用额外的空间,并用O(n)的时间找出所有出现两次的元素。
二、Analyzation
我们可以遍历这个数组,每遇到一个元素x,就看nums[x - 1]上的值是否大于0,若大于0,则让该值置为相反数,反之则说明x是一个重复出现的数,则加入list中。
三、Accepted code
public List<Integer> findDuplicates(int[] nums) {
List<Integer> list = new ArrayList<>();
if(nums == null || nums.length == 0)
return list;
for(int i = 0;i < nums.length;i++){
int index = Math.abs(nums[i]);
if(nums[index - 1] > 0){
nums[index - 1] = - nums[index - 1];
}else{
list.add(Math.abs(nums[i]));
}
}
return list;
}