268. 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. Note: Your algorithm should run in linear runtime complexity.
Could you implement it using only constant extra space complexity?
1.XOR public int missingNumber(int[] nums) { //xor int res = nums.length; for(int i=0; i<nums.length; i++){ res ^= i; res ^= nums[i]; } return res; } 2.SUM public int missingNumber(int[] nums) { //sum int len = nums.length; int sum = (0+len)*(len+1)/2; for(int i=0; i<len; i++) sum-=nums[i]; return sum; } 3.Binary Search public int missingNumber(int[] nums) { //binary search Arrays.sort(nums); int left = 0, right = nums.length, mid= (left + right)/2; while(left<right){ mid = (left + right)/2; if(nums[mid]>mid) right = mid; else left = mid+1; } return left; }