(数组与矩阵) 剑指 Offer 03. 数组中重复的数字 ——【Leetcode每日一题】

❓ 剑指 Offer 03. 数组中重复的数字

难度:简单

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

示例 1:

输入

2, 3, 1, 0, 2, 5, 3

输出:2 或 3

限制

2 < = n < = 100000 2 <= n <= 100000 2<=n<=100000

💡思路:

由于nums中所有的数字都在 0 ~ n-1中,所以可以定义一个长度为 n 的数组cnt:

  • 初始化 cnt0;
  • 遍历 nums
    • cnt[nums[i]]等于0,则 +1;
    • cnt[nums[i]]等于1,则找到重复的数为 nums[i]

🍁代码:(C++、Java)

C++

cpp 复制代码
class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        vector<int> cnt(nums.size());
        for(int num : nums){
            if(cnt[num] == 0) cnt[num]++;
            else return num;
        }
        return -1;
    }
};

Java

java 复制代码
class Solution {
    public int findRepeatNumber(int[] nums) {
        int[] cnt = new int[nums.length];
        for(int num : nums){
            if(cnt[num] == 0) cnt[num]++;
            else return num;
        }
        return -1;
    }
}

🚀 运行结果:

🕔 复杂度分析:

  • 时间复杂度 : O ( n ) O(n) O(n),其中 n 为数组 nums 的长度。
  • 空间复杂度 : O ( n ) O(n) O(n)。

题目来源:力扣。

放弃一件事很容易,每天能坚持一件事一定很酷,一起每日一题吧!
关注我LeetCode主页 / CSDN---力扣专栏,每日更新!

注: 如有不足,欢迎指正!

相关推荐
py有趣13 小时前
力扣热门100题之最小覆盖子串
算法·leetcode
北顾笙98014 小时前
day15-数据结构力扣
数据结构·算法·leetcode
人道领域14 小时前
【LeetCode刷题日记:24】两两交换链表
算法·leetcode·链表
北顾笙98014 小时前
day16-数据结构力扣
数据结构·算法·leetcode
wsoz14 小时前
Leetcode子串-day4
c++·算法·leetcode
会编程的土豆15 小时前
【数据结构与算法】二叉树大总结
数据结构·算法·leetcode
y = xⁿ15 小时前
【LeetCode Hot100】动态规划:T70:爬楼梯 T118:杨辉三角形 T198:打家劫舍
算法·leetcode·动态规划
人道领域15 小时前
【LeetCode 刷题日】19.删除链表的倒数第n个节点
算法·leetcode·链表
py有趣15 小时前
力扣热门100题之最大子数组和
算法·leetcode
小肝一下15 小时前
每日两道力扣,day4
c++·算法·leetcode·职场和发展