-
Notifications
You must be signed in to change notification settings - Fork 43
/
MissingNumber.java
54 lines (43 loc) · 1.44 KB
/
MissingNumber.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package LeetCodeJava.BitManipulation;
// https://leetcode.com/problems/missing-number/?envType=list&envId=xoqag3yj
import java.util.Arrays;
public class MissingNumber {
// V0
// IDEA : MATH
public int missingNumber(int[] nums) {
int n = nums.length;
// NOTE !!! the ordering
int sum_ = ((1+n) * (n)) / 2;
int curSum = Arrays.stream(nums).sum();
//System.out.println("sum_ = " + sum_ + " curSum = " + curSum);
return sum_ - curSum;
}
// V0'
// IDEA : MATH
public int missingNumber_0(int[] nums) {
if (nums.length == 0 || nums == null){
return 0;
}
int _len = nums.length;
int sum1 = Arrays.stream(nums).sum();
int sum2 = ((0 + _len) * (_len+1)) / 2;
return sum2 - sum1;
}
// V1
// IDEA : MATH
// https://leetcode.com/problems/missing-number/solutions/4461518/beats-100-with-java-86-c-easiest-logic-6-lines-code-java-100-runtime/?envType=list&envId=xoqag3yj
public int missingNumber_1(int[]nums) {
//Step1: Find the length of array.
int n = nums.length;
//Step2: Calculate the actual sum using Mathematical formulae
long actualSum = (n*(n+1))/2;
//Step3: Calculate the given sum.
long sum = 0;
for(int element: nums)
{
sum += element;
}
//Step 4: return actualSum-givenSum.
return (int)(actualSum-sum);
}
}