Java O(n) solution with real elegance and works for even Multiple duplicate numbers too!! Enjoy


  • 0
    N

    public int findDuplicate(int[] nums) {
    if (nums.length > 1) {
    for (int i = 0; i < nums.length; i++) {
    if (nums[Math.abs(nums[i])] >= 0)
    nums[Math.abs(nums[i])] = -nums[Math.abs(nums[i])];
    else
    return Math.abs(nums[i]); // Here we can create a list of duplicates in case we have to track multiple duplicate entries in the items.
    }
    }
    return -1;
    }


Log in to reply
 

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