LeetCode:Missing Number And First Missing Positive

redis_v發表於2016-01-11
1、

Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

思路

1:求出1,2......n的數列之和total。

2:計算陣列所有元素的和sum。

3:total - sum的值,就是所求缺失的數。

程式碼:

class Solution {
public:
    int missingNumber(vector<int>& nums) {
	int n = nums.size();
	int total = n * (n + 1) / 2;
	int sum = 0;
	for(int i = 0; i < n; i ++)
	{
		sum += nums[i];
	}
	return total - sum;
}
};

First Missing Positive

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.

思路:

雖然不能再另外開闢非常數級的額外空間,但是可以在輸入陣列上就地進行swap操作。

思路:交換陣列元素,使得陣列中第i位存放數值(i+1)。最後遍歷陣列,尋找第一個不符合此要求的元素,返回其下標。整個過程需要遍歷兩次陣列,複雜度為O(n)

下圖以題目中給出的第二個例子為例,講解操作過程。



程式碼:

class Solution {
public:
void swap(vector<int>& nums, int a, int b)
{
	int tmp = nums[a];
	nums[a] = nums[b];
	nums[b] = tmp;
}
int firstMissingPositive(vector<int>& nums) {
	int n = nums.size();
	int pos = 0;
	while(pos < n)
	{
		int num = nums[pos];
		if(num < n && num > 0 && num != nums[num - 1])
		{
			swap(nums, pos, num - 1);
		}
		else
			pos ++;
	}
	for(int i = 0; i < n; i ++)
	{
		int num = nums[i];
		if(num != i + 1)
			return i + 1;
	}
	return n + 1;
}
};








相關文章