Accepted Simple Java Solution 476 ms


  • -1
    G

    Logic is following
    First consider the boundary conditions when array size is 1

    Since sequences was having a difference of 1 and expected to start with 0 so we do following

    First sort the array

    once array is sorted then we know ( except in 1st iteration ) wherever next number is not 1 more than previous number then we found the missing number which is one more than previous number

    public int MissingNumber(int[] nums) {
    	int retValue=-1;
    	if(nums.length==1){
    		return nums[0]^nums.length;
    	}
    	
    
    	
    	Arrays.sort(nums);
    	for(int k=0;k<nums.length;k++) {
    		if(k==0 && nums[k]>0) {
    			retValue=nums[k]-1;
    		}
    		else if(k<nums.length-1 && nums[k]+1!=nums[k+1]) {
    			retValue=nums[k]+1;
    		}
    	}
    	
    	if (retValue==-1) {
    		retValue = nums[nums.length-1]+1;
    	}
    	System.out.println(retValue);
    	return retValue;
    }

  • 1
    X
    public int missingNumber(int[] nums) {
    
    	//第一种方案
    	/*
    	Arrays.sort(nums);
    	int count = nums.length;
    	int missingNum = -1;
    	
    	for (int i = 0, j = 0; j < count; i++, j++) {
    		if (i != nums[j]) {
    			missingNum = i;
    			break;
    		}
    		if (j == count - 1) {
    			missingNum = ++nums[j];
    			break;
    		}
    	}
    	*/
    	
    	//第二种方案
    	int count = nums.length;
    	int missingNum = nums.length;
    	
    	for (int i = 0 ; i < count; i++) {
    		missingNum += i - nums[i];
    	}
    	return missingNum;
    }

Log in to reply
 

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