Missingnumber problem Description: Given an array, the array number range is 0-n and the missing number is found. such as NUMS={0,1,3},RETURN2.
Algorithm Analysis: The first method, sorting the array, and then find and subscript inconsistent numbers, subscript is the missing number. The second method, for such an array, if there is no missing number, even if there is no sort, the subscript-number difference is added to 0. Assuming that the missing number is in the nums.length position, then sum+nums.length-x = 0;
1 Public intMissingnumber (int[] nums) {2 Arrays.sort (nums);3 for(inti = 0; i < nums.length; i + +)4 {5 if(Nums[i]! =i)6 {7 returni;8 }9 }Ten returnnums.length; One } A - //If there is no missing number, then the sum of the ordinal i-nums[i] is 0; if there is a missing number, then the missing number is in the nums.length position, - //nums.length-x+sum=0;x=nums.length+sum; the Public intMissingNumber2 (int[] nums) { - intsum = 0; - for(inti = 0; i < nums.length; i++) -sum = sum-nums[i] +i; + - returnSum +nums.length; +}
Firstmissingpositive problem Description: For an array that is not sorted, find the first missing positive number, for example nums={1,2,0}return3,nums={3,4,-1,1}return2
Algorithm analysis: Since it is to find a positive number, then it must be starting from 1, then we put 1 in nums[0], and so on, we put each element in the array is where it should be. Then find the subscript and the numbers do not match the element, subscript +1 is the missing positive number.
1 Public Static intFirstmissingpositive (int[] nums) {2 inti = 0;3 //Place each element in the nums in the position of the number it represents, such as nums[1]=4, then nums[1] should be placed in the fourth position, i.e. Nums[1]=nums[nums[1]-1]4 //Exclude negative numbers5 while(I <nums.length)6 {7 if(Nums[i] <= 0 | | nums[i] > Nums.length | | nums[i] = = i + 1 | | nums[i] = = Nums[nums[i]-1])8 {9i++;Ten } One Else A { - inttemp =Nums[i]; -Nums[i] = nums[temp-1]; theNUMS[TEMP-1] =temp; - } - } - intj = 0; + for(j = 0; J < Nums.length; J + +)) - { + if(Nums[j]! = j + 1) A { at returnJ+1; - } - } - returnJ+1; - }
Missingnumber missing digits, firstmissingpositive first missing positive number