LeetCode笔试题 Contains Duplicate

给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:

输入: [1,2,3,1]
输出: true

示例 2:

输入: [1,2,3,4]
输出: false

示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

 这道题不算难题,就是使用一个哈希表,遍历整个数组,如果哈希表里存在,返回false,如果不存在,则将其放入哈希表中,代码如下:

bool containsDuplicate(vector<int>& nums)
{
	//建立一个无序单重映射表
	unordered_map<int, int> m;
	//遍历vec,如果map表中没有找到当前vec的元素,就将其放入map表中。有就直接return
	for (int i = 0; i < nums.size(); ++i) 
	{
		//find函数:在map表中找当前元素,是一个遍历map表的过程,返回值为迭代器
		//找到,迭代器就指向当前位置,找不到就便利到末尾指向end()
		if (m.find(nums[i]) != m.end()) 
			return true;
		//利用operator[]运算符重载将该元素放入map表中。
		++m[nums[i]];
	}
	return false;
}

int main()
{
	vector<int>nums = { 0,1,2,3,4,5,5 };
	if (containsDuplicate(nums))
	{
		cout << "true" << endl;
	}
	else
	{
		cout << "false" << endl;
	}
	getchar();
	return 0;
}

这题还有另一种解法,就是先将数组排个序,然后再比较相邻两个数字是否相等,时间复杂度取决于排序方法,代码如下:

int Compare(const void *num1, const void *num2)
{
	return *(int *)num1 - *(int *)num2;
}
bool containsDuplicate(int *arr, int len)
{
	qsort(arr, len, sizeof(int), Compare);
	for (int i = 0; i < len; i++)
	{
		if (arr[i] == arr[i + 1])
		{
			return true;
		}
	}
	return false;
}
int main()
{
	int arr[] = { 0,1,2,3,3,4 ,1,0 };
	int len = sizeof(arr) / sizeof(arr[0]);

	if (containsDuplicate(arr,len))
	{
		cout << "true" << endl;
	}
	else
	{
		cout << "false" << endl;
	}
	getchar();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhangfei5354/article/details/89677398
今日推荐