(数组与矩阵) 剑指 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有趣7 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣8 小时前
力扣热门100题之回文链表
算法·leetcode·链表
样例过了就是过了11 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz12 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧12 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode
小肝一下13 小时前
每日两道力扣,day2
c++·算法·leetcode·职场和发展
米粒114 小时前
力扣算法刷题 Day 31 (贪心总结)
算法·leetcode·职场和发展
AlenTech14 小时前
647. 回文子串 - 力扣(LeetCode)
算法·leetcode·职场和发展
py有趣15 小时前
力扣热门100题之合并两个有序链表
算法·leetcode·链表
8Qi815 小时前
LeetCode热题100--45.跳跃游戏 II
java·算法·leetcode·贪心算法·编程