442. Find All Duplicates in an Array
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]
本题做法与之前的
1 public class Solution { 2 public List<Integer> findDuplicates(int[] nums) { 3 List<Integer> res = new ArrayList<>(); 4 for(int i=0;i<nums.length;i++){ 5 int num = Math.abs(nums[i]); 6 if(nums[num-1]<0){ 7 res.add(num); 8 }else{ 9 nums[num-1] = -nums[num-1]; 10 } 11 12 } 13 return res; 14 } 15 }