My different way to solve this problem with O(n) time and O(1) space

  • 0
    public class Solution {
        public int findDuplicate(int[] nums) {
            if(nums==null || nums.length<=1)
                return -1;
            for(int i=0;i<nums.length;i++)
                while(nums[i]!=i+1) {
                        return nums[i];
                    int tmp=nums[i];
                    nums[i] = nums[nums[i]-1];
                    nums[tmp-1] = tmp;
            return -1;

Log in to reply

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