消失的数字C/C++

文章目录

  • 1.C++
  • 2.C

1.C++

class Solution 
{
public:
	int missingNumber(vector<int>& nums) 
	{
		unordered_set<int> us;
		int n = nums.size();
		for (int i = 0; i < n; i++)
		{
			us.insert(nums[i]);
		}
		int missing = -1;
		for (int i = 0; i <= n; i++)
		{
			if (us.count(i) == 0) 
			{
				missing = i;
				break;
			}
		}
		return missing;
	}
};

2.C

int missingNumber(int* nums, int numsSize)
{
	int i = 0;
    int sum = (1 + numsSize) * numsSize / 2;

	for (i = 0; i < numsSize; i++)
	{
		sum -= nums[i];
	}
	return sum;
}

你可能感兴趣的:(C家家精品好题,c语言,c++,算法,数据结构)