int comp (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
bool containsDuplicate(int* nums, int numsSize) {
// Sort
qsort(nums, numsSize, sizeof(int), comp);
// Loop
for (int i = 0; i < numsSize - 1; i++) {
if (nums[i] == nums[i+1]) return true;
}
return false;
}
以上为偷学的新技能。
qsort函数stdlib.h文件中,函数原型为
void qsort(void *base,size_t nelem,size_t width,int (*Comp)(const void *,const void *));
*base 为要排序的数组
nelem 为要排序的数组的长度
width 为数组元素的大小(一字节为单位)
默认是从小到大排序的!
bool containsDuplicate(int* nums, int numsSize) {
quicksort(nums,0,numsSize-1);
for(int i=0;i<numsSize-1;i++)
{
if(nums[i]==nums[i++])
return true;
}
return false;
}
void quiksort(int* a,int low,int high)
{
int i = low;
int j = high;
int temp = a[i];
if( low < high)
{
while(i < j)
{
while((a[j] >= temp) && (i < j))
{
j--;
}
a[i] = a[j];
while((a[i] <= temp) && (i < j))
{
i++;
}
a[j]= a[i];
}
a[i] = temp;
quiksort(a,low,i-1);
quiksort(a,j+1,high);
}
else
{
return;
}
}
看我的方法笨拙,固我卡死在栈溢出。
C语言,2016/2/13