Contains Duplicate
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.
代码:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
return nums.size() > set<int>(nums.begin(), nums.end()).size();
}
};
原题地址: https://leetcode.com/problems/contains-duplicate/
以下的做法未通过(Time Limit Exceeded)
void Swap(int *a, int *b);
int Partition(int data[], int length, int start, int end);
void QuickSort(int data[], int length, int start, int end);
bool containsDuplicate(int* nums, int numsSize) {
QuickSort(nums, numsSize, 0, numsSize - 1);
for (int i = 0; i < numsSize - 1; i++)
if (nums[i] == nums[i + 1])
return false;
return true;
}
void QuickSort(int data[], int length, int start, int end)
{
if (start == end)
return;
int index = Partition(data, length, start, end);
if (index > start)
QuickSort(data, length, start, index - 1);
if (index < end)
QuickSort(data, length, index + 1, end);
}
int Partition(int data[], int length, int start, int end)
{
if (data == NULL || length <= 0 || start < 0 || end >= length)
return -1;
int index = start;
Swap(&data[index], &data[end]);
int small = start - 1;
for (index = start; index < end; index++)
{
if (data[index] < data[end])
{
++small;
if (small != index)
Swap(&data[index], &data[small]);
}
}
++small;
Swap(&data[small], &data[end]);
return small;
}
void Swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}