Java in-place sort solution


  • 0
    S
        public List<Integer> findDuplicates(int[] nums) {
            Set<Integer> result = new HashSet<>();
            int n = nums.length, i = 0, temp, num;
            
            while (i < n) {
                while (nums[i] != i + 1) {
                    temp = nums[i];
                    num = nums[temp-1];
                    if (temp == num) {
                        result.add(nums[i]);
                        break;
                    } else {
                        nums[i] = num;
                        nums[temp - 1] = temp;
                    }
                }
                i++;
            }
            return new ArrayList<Integer>(result);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.