(数组与矩阵) 剑指 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---力扣专栏,每日更新!

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

相关推荐
小白菜又菜7 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
superior tigre11 小时前
NumPy 基础使用方法(基础+矩阵运算+Attention)
线性代数·矩阵·numpy
摸个小yu11 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
skywalker_1113 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
生信研究猿13 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
XWalnut13 小时前
LeetCode刷题 day9
java·算法·leetcode
6Hzlia14 小时前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
宵时待雨14 小时前
优选算法专题1:双指针
数据结构·c++·笔记·算法·leetcode
We་ct15 小时前
LeetCode 172. 阶乘后的零:从暴力到最优,拆解解题核心
开发语言·前端·javascript·算法·leetcode·typescript
老虎062715 小时前
LeetCode热题100 刷题笔记(第五天)双指针法 「 三数之和 」
笔记·算法·leetcode