剑指offer题解--⑤数组中重复的数字

数组中重复的数字

https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&&tqId=11203&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

题目分析

这道题可以通过比较当前位置下的值和该值为索引的值比较,从而使得时间复杂度为O(n) ,空间复杂度为O(1)

代码演示

    public boolean duplicate(int numbers[],int length,int [] duplication) {
        //边界值判断
        if (numbers == null || numbers.length == 0){
            duplication[0] = -1;
            return false;
        }
        //循环列表 判断当前位置的值是否与对应索引值相等
        for(int i = 0;i < length ; i++){
            //如果不等的话
            while(numbers[i] != i){
                // 判断该值与该值为索引的值时候相等
                if (numbers[i] == numbers[numbers[i]]){
                    // 如果相等则返回
                   duplication[0] = numbers[i];
                   return true;
                }
                //否则交换
                int temp = numbers[i];
                numbers[i] = numbers[temp];
                numbers[temp] = temp;
            }
        }
        return false;
    }
全部评论

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务