第四周作业1(LeetCode287)

1. 题目描述(LeetCode287)

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:
1.You must not modify the array (assume the array is read only).
2.You must use only constant, O(1) extra space.
3.Your runtime complexity should be less than O(n2).
4.There is only one duplicate number in the array, but it could be repeated more than once.

2. 解决思路

根据题目描述,在一个长度为n+1的整数数组中只包括[1,n]的整数,那么这其中肯定有重复的数。因为题目假设只有一个数重复,且限定不能使用额外的空间,不能改变数组结构,时间复杂度还必须小于O(n)……写到这里自己都怀疑自己是不是做了一道假题……由于自己实在想不出什么好的解决方法,就只得上网求助那些大牛们的博客了。能借鉴别人的方法并最终把它转化为自己的也还是可以的吧,嘿嘿……下面言归正传:

采用二分查找法,因为数出现在[1,n],所以统计[1,n/2]的数,如果出现小于等于n/2的数个数超过n/2,那么[1,n/2]的数中必有重复的数,继续通过二分法减少搜索范围,这里的时间复杂度为O(nlogn)。

3. 完整代码

#include <stdio.h>
#include <stdlib.h>

int FindDuplicateNum(int *array , int len , int left , int right);

int main()
{
    int* array = NULL;
    int len = 0;
    printf("请输入数组的长度:\n");
    scanf("%d" , &len);

    while(len <= 0)
    {
        printf("长度必须大于0,请重新输入:\n");
        scanf("%d" , &len);
    }

    array = (int*)malloc(sizeof(int)*len);//数组分配内存
    printf("请输入1到%d之间的整数且重复数字只允许有一个:\n",len-1);

    for(int i = 0; i < len; i++)
    {
        scanf("%d" , &array[i]);
    }

    //调用封装好的功能函数
    int left = 0 , right = len - 1;
    int result = FindDuplicateNum(array , len , left ,right);

    printf("数组中重复的数字是:%d\n" , result);

    scanf("%d" , &len);//加个输入让窗口停下来
    free(array);//释放内存

}


 int FindDuplicateNum(int *array , int len , int left , int right)
 {
     int count;

     while(left < right)
     {
         int mid = left + (right - left)/2;
         count = 0;

        for(int i = 0; i < len; i++)  //统计出数组中不大于中间元素值的个数
        {
            if(array[i] <= mid)
                count++;
        }

        if(count > mid)
            right = mid;
        else
             left = mid + 1;

     }
     return left;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值