java o(n) no extra space


  • 0
    Y
    public class Solution {
        public List<Integer> findDuplicates(int[] nums) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                nums[i]--;
            }
            for (int i = 0; i < nums.length; i++) {
                int val = nums[i];
                if (i != val) {
                    while(nums[i] != i && nums[i] != nums[val]) {
                        nums[i] = nums[val];
                        nums[val] = val;
                        val = nums[i];
                    }
                }
            }
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != i) list.add(nums[i]+1);
            }
            return list;
        }
    }
    

Log in to reply
 

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