forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
missing-number.java
39 lines (31 loc) · 935 Bytes
/
missing-number.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Time Complexity - O(n)
* Space Complexity - O(1)
*
* Please comment one of the method if you are submitting solution directly
*/
class Solution {
// Using sum of first n natural numbers formula.
public int missingNumber(int[] nums) {
int numsLen = nums.length;
// sum of n natural number is
// Sn = n * (n+1)/2
int expectedSum = numsLen*(numsLen+1)/2;
// calculate actual sum
int actualSum = 0;
for (int i=0; i<numsLen; i++){
actualSum += nums[i];
}
// subtract actualSum from expectedSum
return expectedSum-actualSum;
}
// Using XOR approach
public int missingNumber(int[] nums) {
int numsLen = nums.length;
int xor = numsLen;
for(int i=0; i<numsLen; i++){
xor ^= nums[i] ^ i;
}
return xor;
}
}