Easy understood java solution O(n) time and O(1) space


  • -1
    G

    change the corresponding element into negative, if one element is already negative, the number corresponding to this index is the duplicated one.

    public int findDuplicate(int[] nums) {
            for (int num : nums) {
                int index = Math.abs(num) - 1;
                if (nums[index] < 0) {
                    return Math.abs(num);
                } else {
                    nums[index] = - nums[index];
                }
            }
            return -1;
     }
    

Log in to reply
 

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