首页 > 其他分享 >Contains Duplicate

Contains Duplicate

时间:2022-12-13 16:06:18浏览次数:53  
标签:numsSize return nums int Contains Duplicate key false


​https://leetcode.com/problems/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.

方法一,想到的简单方法

int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}

bool containsDuplicate(int* nums, int numsSize) {
int i;

//
qsort(nums, numsSize, sizeof(nums[0]), cmp);

for(i = 1; i < numsSize; ++i) {
if(nums[i] == nums[i-1])
return true;
}

return false;
}

方法二,基于插入排序改进,效率更高

bool containsDuplicate(int* nums, int numsSize) {
int i, j, key;

for(i = 1; i < numsSize; ++i) {

j = i -1;
key = nums[i];
while(j > 0 && nums[j] > key) {
nums[j + 1] = nums[j]; // move to back
j--;
}

if(j != (i-1))
nums[j + 1] = key;

if(nums[j] == key)
return true;
}

return false;
}


标签:numsSize,return,nums,int,Contains,Duplicate,key,false
From: https://blog.51cto.com/u_15911341/5934358

相关文章