当前位置:网站首页>剑指 Offer 03. 数组中重复的数字
剑指 Offer 03. 数组中重复的数字
2022-06-25 15:32:00 【anieoo】

solution:
哈希表存储出现过的数字,时间复杂度O(n)
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
unordered_set<int> map;
for(auto &x : nums) {
if(map.count(x)) return x;
map.insert(x);
}
return 0;
}
};排序+遍历,时间复杂度O(nlogn)
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;
}
};给定元素一定在0~n - 1,如果出现次数都为1,一定可以交换到正确的位置。
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
for(int i = 0;i < nums.size();i++) {
while(nums[i] != i) {
if(nums[nums[i]] == nums[i]) return nums[i];
swap(nums[nums[i]], nums[i]);
}
}
return 0;
}
};边栏推荐
- Breakpad usage and DMP analysis
- Fishing detection software
- Single user mode
- JSON module dictionary and string conversion
- Data feature analysis skills - correlation test
- Detailed description of crontab command format and summary of common writing methods
- Custom structure type
- [paper notes] semi supervised object detection (ssod)
- Some usage records about using pyqt5
- [C language] 32 keyword memory skills
猜你喜欢

Fishing detection software

Common dynamic memory errors

Data feature analysis skills - correlation test

Generic - learning notes

Judging the number of leap years from 1 to N years

Could not connect to redis at 127.0.0.1:6379 in Windows

Learning notes on February 8, 2022 (C language)

Kali SSH Remote Login

Graphic control and layout basis of R visualization

QT pattern prompt box implementation
随机推荐
Iterator failure condition
Solution of push code failure in idea
Several common optimization methods
Image segmentation based on deep learning: network structure design
Getting started with lambda8 new features
Internal class learning notes
The difference between sizeof and strlen
QT loading third-party library basic operation
Semaphore function
High precision addition
Arthas source code learning-1
MySQL field truncation principle and source code analysis
Learning notes on February 8, 2022 (C language)
在国信金太阳开股票账户安全吗?
[paper notes] mcunetv2: memory efficient patch based influence for tiny deep learning
Leetcode123 timing of buying and selling stocks III
Boost listening port server
Sampling method and descriptive statistical function in R language
Simulating Sir disease transmission model with netlogo
Generic - learning notes