Somewhat DFS solution


  • 0
    B

    This solution has some DFS flavor

    public class Solution {
        public List<Integer> findDuplicates(int[] nums) {
            for (int i = 0; i < nums.length; i++) {
                
                // Start from some node we haven't visited before
                if (nums[i] > 0) {
                    int index = nums[i];
                    
                    while (index > 0) {
                        if (nums[index-1] < 0) {
                            nums[index-1]--;
                            break; // We reached some node we visited before
                        } else {
                            int tmp = nums[index-1];
                            nums[index-1] = -1;
                           // Prevent cycle
                            if (index-1 <= i) break;
                            index = tmp;
                        }
                    }
                }
            }
            
            List<Integer> list = new LinkedList<Integer>();
            
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == -2) {
                    list.add(i+1);
                }
            }
            
            return list;
        }
    }
    

Log in to reply
 

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