Java val-to-index solution


  • 0
    D
    public class Solution {
        public List<Integer> findDuplicates(int[] nums) {
            List<Integer> duplicates = new ArrayList<>();
            if (nums == null || nums.length <= 1) {
                return duplicates;
            }
            for (int i = 0, dup; i < nums.length; i++) {
                if ((dup = verifyDuplicate(nums, i)) != -1) {
                    duplicates.add(dup);
                }
            }
            return duplicates;
        }
    
        private int verifyDuplicate(int[] nums, int index) {
            int thisjump = nums[index];
            nums[index] = -1;
            while (true) {
                int thatjump = nums[thisjump - 1];
                if (thatjump == -1) {
                    nums[thisjump - 1] = thisjump;
                    return -1;
                } else if (thatjump == thisjump) {
                    return thisjump;
                } else {
                    nums[thisjump - 1] = thisjump;
                    thisjump = thatjump;
                }
            }
        }
    }
    

Log in to reply
 

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