Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array.
Have you met this question in a real interview?
Yes
Example
Given N =
3
and the array [0, 1, 3]
, return 2
.
Challenge
Do it in-place with O(1) extra memory and O(n) time.
public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int findMissing(int[] nums) {
// write your code here
int n = nums.length;
int sum = (n+1) * n / 2;
for(int num : nums){
sum -= num;
}
return sum;
}
}
public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int findMissing(int[] nums) {
// write your code here
int xor = 0;
for(int i = 0; i <= nums.length; i++){
xor ^= i;
}
for(int num : nums){
xor ^= num;
}
return xor;
}
}
No comments:
Post a Comment