数组中重复的数字
Category | Difficulty | Likes | Dislikes |
---|---|---|---|
lcof | Easy (67.85%) | 936 | - |
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
分析:
排序后找重复值即可
代码:
/*
* @lc app=leetcode.cn id=100275 lang=cpp
*
* [剑指 Offer 03] 数组中重复的数字
*/
// @lc code=start
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
for(int i=1; i < nums.size(); i++){
if(nums[i] == nums[i-1])
return nums[i];
}
return 0;
}
};
// @lc code=end
Accepted
- 27/27 cases passed (32 ms)
- Your runtime beats 76.19 % of cpp submissions
- Your memory usage beats 65.98 % of cpp submissions (22.4 MB)