Just for sharing

  • 0

    from the problem, I notice the input is in 1 to n. We can use it as the index. It may be posted by other people before.

    public int findDuplicate(int[] nums) {
    for(int num : nums){
         int idx = Math.abs(num) - 1;
         if(nums[idx] < 0){
             return idx + 1;
             nums[idx] = -nums[idx];
    return 0; //if the input is valid, we should output in for loop.

Log in to reply

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