Java O(n) not using sum


  • 1
    V
    public int missingNumber(int[] nums) {
        int i;
        for (i=0;i<nums.length;i++) {
            while (nums[i]!=i && nums[i]!=nums.length) {
                int num = nums[i];
                int tmp = nums[num];
                nums[num] = num;
                nums[i]=tmp;
            }
        }
        if (nums[0]!=0) return 0;
        for (i=1;i<nums.length;i++) {
            if (nums[i]!=nums[i-1]+1) break;
        }
        return i;
    }

Log in to reply
 

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