Find Missing Number 系列问题,灵活运用index,或异或在O(n)时间复杂度,O(1)空间复杂度解决问题。
题目
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
- 解法一 O(nlogn) time and O(1) space
public int FirstMissingPositive(int[] nums)
{
//O(nlogn) time and O(1) space
for (int i = 1; i <= nums.Length + 1; i++)
{
if (!nums.Contains(i)) //O(log(n))
return i;
}
return 1;//nums=[], return 1
}
- 解法二
O(n) time and O(1) space
思路:
if element nums[i] > 0 && nums[i]-1 < nums.Length, swap nums[i] to nums[nums[i]-1].
public int FirstMissingPositive2(int[] nums)
{
//O(n) time and O(1) space
//if element nums[i] > 0 && nums[i]-1 < nums.Length,
// swap nums[i] to nums[nums[i]-1].
int rtn = nums.Length + 1; //such as nums=[2,4,-1,3], return 1
for (int i = 0; i < nums.Length; i++)
{
while (swap(nums, i, nums[i] - 1)) ;
}
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != i + 1)
return i + 1;
}
return rtn;
}
private bool swap(int[] nums, int i, int j)
{
if (j >= 0 && j < nums.Length && nums[i]!=nums[j])
{
int tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
return true;
}
return false;
}
其他相似问题1:
//assert: all positives and only missing a number,
//such as [3,1,4], return missing number 2
//time complexity:O(n); space complexity:O(1)
public int findMissing(int[] nums)
{
int rtn = 0;
for (int i = 1; i <= nums.Length; i++)
rtn ^= i ^ nums[i - 1];
return rtn ^ (nums.Length + 1);
}
其他相似问题2:
//assert: only containing one negative number,
//such as [3,-1,2,4], find the only missing positive number,1
//time complexity:O(n); space complexity:O(1)
public int findMissing2(int[] nums)
{
int rtn = 0;
for (int i = 1; i <= nums.Length; i++)
{
if (nums[i - 1] < 0)
{
rtn = rtn ^ i;
continue;
}
rtn ^= i ^ nums[i - 1];
}
return rtn;
}