Java Solution with O(n) Time & O(1) Space


  • 0
    C
    public class Solution {
        public int missingNumber(int[] nums) {
            int indexZero = -1, flipZero = 0;
            for (int i = 0; i < nums.length; i++) {
                int abs = Math.abs(nums[i]);
                if (abs < nums.length) nums[abs] = -nums[abs];
                if (abs == 0) indexZero = i;
            }
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] > 0) return i;
                if (Math.abs(nums[i]) == indexZero) flipZero = 1;
            }
            return flipZero == 1 ? nums.length : indexZero;
        }
    }

Log in to reply
 

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