题目描述
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.
题目大意:
样例
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
python解法
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return True if len(set(nums))<len(nums) else False
Runtime: 148 ms, faster than 36.07% of Python3 online submissions for Contains Duplicate.
Memory Usage: 19.2 MB, less than 16.98% of Python3 online submissions for Contains Duplicate.
题后反思:
- 一句话搞定!
C语言解法
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
bool containsDuplicate(int* nums, int numsSize){
if (numsSize == 0 || numsSize == 1)
return false;
qsort(nums, numsSize, sizeof(nums[0]), cmp);
for(int i=0;i < numsSize-1;i++)
{
if (nums[i] == nums[i+1])
return true;
}
return false;
}
Runtime: 28 ms, faster than 42.42% of C online submissions for Contains Duplicate.
Memory Usage: 9.7 MB, less than 100.00% of C online submissions for Contains Duplicate.
题后反思:无
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步