This is the program to find the missing numbers in the first n integers.
public static int findMissingNumber(int[] nums) {
int n = nums.length + 1;
// formula for sum of first n integers is n*(n+1)/2
// but we have n+1 integers as one integer is missing
int sum = (n * (n + 1)) / 2;
for (int i = 0; i < nums.length; i++) {
sum -= nums[i];
}
return sum;
}
No comments:
Post a Comment