286. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
public class Solution { public int missingNumber(int[] nums) { int len = nums.length; if(len == 0) return 0; int largestAt = -1;//the index denoting where the largest number is int left = 0; while(left<len){ int current = nums[left]; if(current == left) ++left; else if(current == len){ largestAt = left; ++left; } else{ int temp = nums[current]; nums[current] = current; nums[left] = temp; } } if(largestAt == -1) //cannot find largest number return len; else return largestAt; } }
Bit Solution: XOR collecting all numbers and indices. Only the number that appears only once will be left.
public class Solution { public int missingNumber(int[] nums) { int xor = nums.length; for (int i = 0; i < nums.length; i++) { xor = xor ^ i ^ nums[i]; } return xor; } }
41. First Missing Positive
Given an unsorted integer array, find the first missing positive integer.For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
Solution:
The idea is to put the number at its right place. For example, 1 should be put at index 0, 2 should be put at index 1, etc..
If you see a number that is 0, or negative, or larger the the array length, you know it doesn't make any contribution to the positive number sequence, therefore it's a garbage number. Swap a garbage number to the end of the array. There is another case where garbage number could occur, which is a duplicated good number. Only the first good number can make contribution.
Use garbage as an index to keep garbage numbers. Move this index left-ward after finding each garbage number.
public class Solution { public int firstMissingPositive(int[] nums) { int len = nums.length; if(len == 0) return 1; int garbage = len-1; int ci = 0; //current_index while(ci<garbage){ int current = nums[ci]; if(current == ci+1) //expecting this ++ci; else if(current>0 && current<=len){ //this is a valuable number, there is a corresponding position for this number //the position is current-1. int destVal = nums[current-1]; if(destVal == current){ //already have this number as a duplicate, this number is a garbage number now. Swap it to the end. int temp = nums[garbage]; nums[garbage] = current; nums[ci] = temp; --garbage; } else{//place current at (current-1) nums[current-1] = current; nums[ci] = destVal; } } else{//this is a garbage number, swap it to the end. int temp = nums[garbage]; nums[garbage] = current; nums[ci] = temp; --garbage; } } //final check when ci == garbage if(nums[ci] == ci+1){ return ci+2; } else{ return ci+1; } } }