leetcode 217. Contains Duplicate(C语言,堆排序,查重)23

以下为原创,如有错误,还望指出

贴原题:

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twicein the array, and it should return false if every element is distinct.

解析:
  题目很简短也很简单,就是给出一个数组,如果有重复元素则返回true,否则返回false。
  我的思路是进行排序,然后进行扫描,如果存在相邻两个数相等即为有重复元素,返回true,否则返回false。
  堆排序我在另一题里已经写了注释,这里贴出链接:
  “leecode 169. Majority Element(C语言,快速排序,堆排序,各类排序算法复杂度比较)22 - 我选择登月的博客 - CSDN博客”
http://blog.csdn.net/m0_37454852/article/details/78156566

C代码:

void headAjuast(int* nums, int root, int len)
{
    int lChild=root*2;
    int rChild=lChild+1;
    int largest=root;
    if(lChild<len && *(nums+lChild)>*(nums+largest))
    {
        largest=lChild;
    }
    if(rChild<len && *(nums+rChild)>*(nums+largest))
    {
        largest=rChild;
    }
    if(largest!=root)
    {
        *(nums+root)=*(nums+root)^(*(nums+largest));
        *(nums+largest)=*(nums+root)^(*(nums+largest));
        *(nums+root)=*(nums+root)^(*(nums+largest));
        headAjuast(nums, largest, len);
    }
}
bool heapSort(int* nums, int len)
{
    for(int i=len/2; i>=0; i--)
    {
        headAjuast(nums, i, len);
    }
    for(int i=len-1; i>0; i--)
    {
        *nums=*nums^(*(nums+i));
        *(nums+i)=*nums^(*(nums+i));
        *nums=*nums^(*(nums+i));
        if(i<len-1 && *(nums+i)==(*(nums+i+1)))
        {
            return true;
        }
        headAjuast(nums, 0, i);
    }
    if(len>=2 && *nums==*(nums+1))
    {
        return true;
    }
    return false;
}
bool containsDuplicate(int* nums, int numsSize) {
    return heapSort(nums, numsSize);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值