Contains Duplicate

原创 2016年08月29日 00:40:00
given an array of integers, find if the array contains any duplicates.
your function should return true if any value appears at least twice in the array, 

and it should return false if every element is distinct.

//solution1 time(O(n^2))
bool containsDuplicate1(int* nums, int numsSize) {
	int* p = nums;
	int* q = nums + numsSize - 1;
	int* cursor = NULL;
	bool result = true;
	while (q - p>0)
	{
		cursor = p + 1;
		while (q - cursor >= 0)
		{
			if (*cursor == *p)
				return true;
			else
			{
				++cursor;
			}
		}
		++p;
	}
	return false;

}

//solution2 time(O(n))
bool containsDuplicate2(int* nums, int numsSize) {
	bool result = true;
	if (numsSize == 0)
		result = false;
	int hashkey[numsSize];
	int hashvalue[numsSize];
	for (int k = 0; k != numsSize; ++k)
		hashvalue[k] = 0;

	for (int i = 0; i != numsSize; ++i)
	{
		int id = (nums[i] + numsSize) % numsSize;
		if (hashvalue[id] == 0)
		{
			++hashvalue[id];
			hashkey[id] = nums[i];
		}
		else if (hashkey[id] == nums[i])
			++hashvalue[id];
		else
		{
			while (hashvalue[id] != 0)
			{
				id = (id + 1) % numsSize;
			}
			hashkey[id] = nums[i];
			hashvalue[id] += 1;
		}
	}
	for (int j = 0; j != numsSize; ++j)
	{
		if (hashvalue[j] >= 2)
		{
			result = true;
			break;
		}
		else
			result = false;
	}
	return result;
}






【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II(包含重复元素II)】

【219-Contains Duplicate II(包含重复元素II)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】代码下载【https://github.com/Wang-...

[217] Contains Duplicate

判定一个数组中是否包含重复的数字。
  • camlot_
  • camlot_
  • 2016年06月26日 15:35
  • 114

Leetcode 219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j...

LeetCode #217 Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return t...

[leetcode]: 219. Contains Duplicate II

1.题目Given an array of integers and an integer k, find out whether there are two distinct indices i a...

Leetcode220-Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...

[Leetcode]Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array su...

LeetCode|Contains Duplicate*

Contains DuplicateGiven an array of integers, find if the array contains any duplicates. Your functi...

LEETCODE-Contains Duplicate

Contain Duplicate Given an array of integers, find if the array contains any duplicates. Your funct...

LeetCode 217 Contains Duplicate(包含重复数字)(Vector、hash)

翻译给定一个整型数字数组,找出这个数组是否包含任何重复内容。如果任何值出现了至少两次,那么返回真(true),如果每个值都是互不相同的,那么返回假(false)。原文Given an array of...
  • NoMasp
  • NoMasp
  • 2016年01月12日 14:41
  • 1576
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Contains Duplicate
举报原因:
原因补充:

(最多只允许输入30个字)