-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMissNo0toN_268
40 lines (35 loc) · 883 Bytes
/
MissNo0toN_268
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
Leetcode - 268
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
my code---
class Solution {
public int missingNumber(int[] nums) {
int k = nums.length;
int j=0,p=1;
while(j<=k){
for(int i=0;i<nums.length;i++){
if(j==nums[i]){
j++; p=0;
break;
}
else
p=1;
}
if(p==1)
return j;
}
return 0;
}
}
Optimised Code --
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int sum = 0;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
}
int expectedSum = (n*(n+1))/2; //6
int missingNumber = expectedSum - sum; // 6 - 4
return missingNumber;
}
}