当前位置:网站首页>剑指 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;
}
};边栏推荐
- Go language template text/template error unexpected EOF
- QT animation loading and closing window
- Simulating Sir disease transmission model with netlogo
- Luogu p5707 [deep foundation 2. example 12] late for school
- Two advanced playing methods of QT signal and slot
- Learning notes on February 8, 2022 (C language)
- Go build reports an error missing go sum entry for module providing package ... to add:
- JMeter reading and writing excel requires jxl jar
- MySQL field truncation principle and source code analysis
- Breakpad usage and DMP analysis
猜你喜欢

Learning notes on February 18, 2022 (C language)

Solution of push code failure in idea

Mining procedure processing

JS select all exercise

Introduction to flexible array

Generic - learning notes

Simulating Sir disease transmission model with netlogo

basic_ String mind map

Judging the number of leap years from 1 to N years

Learning C language today is the first time to learn C language. In college, C linguistics is not good, but I want to make progress, so I found a beep video on the Internet to learn C language
随机推荐
System Verilog - function and task
System Verilog — interface
Reflection - learning notes
55 specific ways to improve program design (2)
[paper notes] rethinking and improving relative position encoding for vision transformer
Summary of common methods of ArrayList, LinkedList and vector, and analysis of source code learning
QT source code online view
Go build reports an error missing go sum entry for module providing package ... to add:
semget No space left on device
A deformation problem of Hanoi Tower
Solution of push code failure in idea
User defined data type - structure
Why should the coroutine be set to non blocking IO
Introduction to flexible array
JSON module dictionary and string conversion
Brain tree (I)
The difference between sizeof and strlen
[paper notes] poly yolo: higher speed, more precise detection and instance segmentation for yolov3
Getting started with lambda8 new features
Globally unique key generation strategy - implementation principle of the sender