(数组与矩阵) 剑指 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:

  • 初始化 cnt 为 0;
  • 遍历 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---力扣专栏,每日更新!

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

相关推荐
Dream it possible!8 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊8 小时前
算法之双指针系列(一)
算法·leetcode
Pniubi10 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
Pniubi11 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
文丑颜不良啊16 小时前
LeetCode2081~2100题目解析
java·leetcode
文丑颜不良啊17 小时前
LeetCode2061~2080题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode1941~1960题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2001~2020题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2021~2040题目解析
java·leetcode