Short Java Solution with O(n) time complexity and O(1) space


  • 0
    M

    Simple Java Solution -- put all elements at their proper positions and return the element which still remains at the incorrect position

    public class Solution {        
        public int findDuplicate(int[] nums) {
            if (nums.length==0) {return -1;}
            for (int i=0;i<nums.length;i++) {
                while(nums[i]>=0 && nums[i]<nums.length && nums[nums[i]-1]!=nums[i]) {
                    int temp = nums[i];
                    nums[i] = nums[nums[i]-1];
                    nums[temp-1] = temp;
                }
            }
            
            for (int i=0;i<nums.length;i++) {
                if (nums[i]!=i+1) {return nums[i];}
            }
            return nums.length;
        }
    }

Log in to reply
 

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