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]
和leetcode448 Find All Numbers Disappeared In An Array Java
问题基本一样。思路是把数组中的数值当做下标进行处理。public List<Integer> findDuplicates(int[] nums) { List<Integer> result = new ArrayList<>(); for(int i=0; i<nums.length; i++) { int currNum = Math.abs(nums[i]); if(nums[currNum - 1] > 0) { nums[currNum - 1] = -nums[currNum - 1]; }else { result.add(currNum); } } return result; }