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]
My Solutions:
Use index positions as the "real" numbers. To indicate visited, make it negative. Second time you see negative number means a duplicate so add to list.
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> newList = new ArrayList<Integer>(); // creating a new List
for(int i = 0; i < nums.length; i++){
int index = Math.abs(nums[i]); // Taking the absolute value to find index
if (nums[index - 1] > 0){
nums[index - 1] = -nums[index - 1];
} else{ // If it is not greater than 0 (i.e) negative then the number is a duplicate
newList.add(Math.abs(nums[i]));
}
}
return newList;
}
}
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int val = Math.abs(nums[i]) - 1;
if (nums[val] > 0) nums[val] = -nums[val];
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) list.add(i + 1);
}
return list;
}
}