49. Missing Number
16 Jul 2020 | Daily Algorithms
My Solution
class Solution {
public:
int missingNumber(vector<int>& nums) {
if(nums.size()==1 && nums[0]==1)
{
return 0;
}
if(nums.size() == 1 && nums[0] == 0)
{
return 1;
}
int current_sum = 0;
int max = INT_MIN;
int min = INT_MAX;
for(int i : nums)
{
current_sum = current_sum + i;
if(max<i)
{
max = i;
}
if(min>i)
{
min = i;
}
}
int expected_sum = 0;
for(int i = 0; i<=max; i++)
{
expected_sum = expected_sum + i;
}
if(expected_sum - current_sum == 0)
{
if(min!=0)
{
return 0;
}
else
{
return max+1;
}
}
return expected_sum - current_sum;
}
};
My Solution
class Solution {
public:
int missingNumber(vector<int>& nums) {
if(nums.size()==1 && nums[0]==1)
{
return 0;
}
if(nums.size() == 1 && nums[0] == 0)
{
return 1;
}
int current_sum = 0;
int max = INT_MIN;
int min = INT_MAX;
for(int i : nums)
{
current_sum = current_sum + i;
if(max<i)
{
max = i;
}
if(min>i)
{
min = i;
}
}
int expected_sum = 0;
for(int i = 0; i<=max; i++)
{
expected_sum = expected_sum + i;
}
if(expected_sum - current_sum == 0)
{
if(min!=0)
{
return 0;
}
else
{
return max+1;
}
}
return expected_sum - current_sum;
}
};
Comments