当前位置:网站首页>剑指 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;
}
};边栏推荐
- 客户经理给的开户链接办理股票开户安全吗?我想开个户
- Day01: learning notes
- Shared memory synchronous encapsulation
- basic_ String mind map
- QT article outline
- Basic syntax and common commands of R language
- Globally unique key generation strategy - implementation principle of the sender
- Cross compilation correlation of curl Library
- If a thread overflows heap memory or stack memory, will other threads continue to work
- Netlogo learning
猜你喜欢

Architecture evolution of high-performance servers -- Suggestions

Learning notes on February 18, 2022 (C language)

Simulating Sir disease transmission model with netlogo

Distributed transaction solution

Postman usage notes, interface framework notes
![[paper notes] street view change detection with deconvolutional networks](/img/2d/777fd0d85ff4d349516b95923410fd.jpg)
[paper notes] street view change detection with deconvolutional networks

Agent and classloader

Design and implementation of thread pool

Some usage records about using pyqt5

Qcodeeditor - QT based code editor
随机推荐
Qlogsystem log system configuration use
(2) Relational database
在国信金太阳开股票账户安全吗?
QT source code online view
Two advanced playing methods of QT signal and slot
Architecture evolution of high-performance servers -- Suggestions
Reflection - learning notes
Judging the number of leap years from 1 to N years
Stderr and stdout related standard outputs and other C system APIs
Several common optimization methods
Kali modify IP address
Fishing detection software
Review of arrays and pointers triggered by a topic
Learning notes on February 8, 2022 (C language)
Qmake uses toplevel or topbuilddir
Arthas source code learning-1
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
Using Visual Studio
Generic - learning notes
Postman usage notes, interface framework notes