Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

442. Find All Duplicates in an Array #169

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public List findDuplicates(int[] nums) { //1 ≤ a[i] ≤ n (n = size of array),把每个元素变成负数,if判断,如果元素是负数,则出现过 List res = new ArrayList(); for(int i = 0; i < nums.length; i++) { int index = Math.abs(nums[i]) - 1; if(nums[index] < 0) res.add(Math.abs(index) + 1); nums[index] = -nums[index]; } return res; } }