JAVA Solution by Exchanging Positions, though not sure if it's O(n) time


  • 0
    E
    public class Solution {
        public int missingNumber(int[] nums) {
            int i = 0;
            while(i<nums.length){
                if(nums[i]!=i){
                    try{
                        int temp = nums[nums[i]];
                        nums[nums[i]] = nums[i];
                        nums[i] = temp;
                    }catch(Exception e){
                        if(nums[i]!=nums.length){
                            return nums.length;
                        }
                        i++;
                    }
                }else{
                    i++;
                }
            }
    
            for(int j=0;j<nums.length;j++){
                if(nums[j]!=j){
                    return j;
                }
            }
            return nums.length;
        }
    }

Log in to reply
 

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