Leetcode ☞ 217. Contains Duplicate

本文介绍了一种解决LeetCode上217题含有重复元素的方法,通过双重循环检查数组中是否存在重复元素,并提出了通过排序来优化算法效率的方案。

网址:https://leetcode.com/problems/contains-duplicate/

217. Contains Duplicate

My Submissions
Total Accepted: 71959  Total Submissions: 178180  Difficulty: Easy

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.







我的AC:

bool containsDuplicate(int* nums, int numsSize) {
    int i, j;
    for(i = 0; i < numsSize ; i ++){
        for(j = i + 1 ; j <numsSize; j++){
            if (nums[i] == nums[j])
                return true;
        } 
    }
    return false;
}

缺点:1568ms。时间太长。如果先把nums数组排序再进行比较,就快的多了(仅需比较相邻的是否相同)。

改进:

int comp(const int *a, const int *b) {  
    if (*a > *b) return 1;  
    else if (*a < *b) return -1;  
    else return 0;  
}  
  
bool containsDuplicate(int* nums, int numsSize) {  
    if (numsSize < 2) {  
        return false;  
    }  
    qsort(nums, numsSize, sizeof(int), comp);  
    for (int i = 0; i < numsSize - 1; i++) {  
        if (nums[i] == nums[i+1]) {  
            return true;  
        }  
    }  
    return false;  
}  

其中comp函数也可以写成:

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












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值