268. Missing Number
1. Description
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.
2. Follow Up
Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
3. Example
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
Example 4:
Input: nums = [0]
Output: 1
Explanation: n = 1 since there is 1 number, so all numbers are in the range [0,1]. 1 is the missing number in the range since it does not appear in nums.
4. Note
- n == nums.length
- 1 <= n <= $10^4$
- 0 <= nums[i] <= n
- All the numbers of nums are unique.
5. Solutions
My Accepted Solution(Follow Up)
n = i_nums.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
public:
// int missingNumber(vector<int>& nums)
int missingNumber(const vector<int> &i_nums)
{
int missingNumber = i_nums.size();
for(int i = 0; i <i_nums.size(); i++)
{
missingNumber = missingNumber ^ i ^ i_nums[i];
}
return missingNumber;
}
};
5.1 Hash Table
n = i_nums.size()
Time complexity: O(n)
Space complexity: O(n)
class Solution
{
public:
// int missingNumber(vector<int>& nums)
int missingNumber(const vector<int> &i_nums)
{
vector<int> occur(i_nums.size()+1);
for(auto number : i_nums)
{
occur[number]++;
}
for(int i = 0; i < occur.size(); i++)
{
if(occur[i] == 0) return i;
}
return 0; // meaningless, for compile check
}
};
5.2 Return to Own Position(Follow Up)
n = m_nums.size()
Time complexity: O(n)
Space complexity: O(1)
// if we let all numbers go back to its correct positon, that's means, m_nums[i] == i
// the only number, whose index not equals to its value, is the missing number
class Solution
{
public:
// int missingNumber(vector<int>& nums)
int missingNumber(vector<int> &m_nums)
{
m_nums.push_back(-1);
for(int i = 0; i < m_nums.size(); i++)
{
while(m_nums[i] != i && m_nums[i] != -1)
{
swap(m_nums[i], m_nums[m_nums[i]]);
}
}
for(int i = 0; i < m_nums.size(); i++)
{
if(m_nums[i] == -1)
return i;
}
return 0; // meaningless, for compile check
}
};
5.3 Calculate Sum(Follow Up)
n = i_nums.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
public:
// int missingNumber(vector<int>& nums)
int missingNumber(const vector<int> &i_nums)
{
int sum = accumulate(i_nums.begin(), i_nums.end(), 0);
int correctSum = (1+i_nums.size()) * i_nums.size() / 2;
return correctSum - sum;
}
};