当前位置:网站首页>Hash table questions (Part 2)
Hash table questions (Part 2)
2022-07-27 04:30:00 【std i hurt o love】
One 、 Missing first positive integer
There is a problem with this question , Division solution one , Solution four sides , Other solutions apply to non repeating elements
Solution 1 : Hashtable ( recommend )
- use unordered_map Create a hash table , Record the numbers that appear in the array
- from 1 So let's start walking through n, Query whether the hash table has this number , Without it, the first missing positive integer in the array
- If the traversal finally finds , Then it is true that n+1 individual
class Solution {
public:
int minNumberDisappeared(vector<int>& nums) {
// write code here
int n=nums.size();
unordered_map<int,int>um;
for(int i=0;i<n;i++)
um[nums[i]]++;// Record the data that appears
int pos=1;
while(um.find(pos)!=um.end())
pos++;
return pos;
}
};
Time complexity :O(n), Traversing the array for the first time , by O(n), The second worst is from 1 Traversing n, by O(n)
Spatial complexity :O(n), Hash table records n A non repeating element , The length is n
Solution 2 : In situ hash
- First traverse the array and change all negative numbers to n+1
- Traversal array again , When the absolute value of the number encountered does not exceed n when , Indicates the element bit 1~n Elements in , Change the element in the subscript corresponding to this value to a negative number , It is equivalent that the subscripts of positive integers that have appeared point to a negative number , This is an operation similar to the implementation principle of hash table
- Finally, we traverse the array , The first non negative subscript encountered is the missing positive integer
class Solution {
public:
int minNumberDisappeared(vector<int>& nums) {
// write code here
int n=nums.size();
for(int&i:nums)
if(i<=0)
i=n+1;// Negative numbers are marked n+1
for(int&i:nums)
if(abs(i)<=n)
nums[abs(i)-1]=-1*abs(nums[abs(i)-1]);// Mark the subscript of the number as negative
for(int i=0;i<n;i++)
if(nums[i]>0)// Find the first non negative subscript
return i+1;
return n+1;
}
};
Time complexity :O(n), Traverse the array many times , It's all single-layer circulation
Spatial complexity :O(1), In situ hash , Point to the index , There is no extra space
Solution 3 : Sort
class Solution {
public:
int minNumberDisappeared(vector<int>& nums) {
// write code here
sort(nums.begin(),nums.end());
int n=nums.size(),ct1=0,ct2=0;
for(int&i:nums)
{
if(i<=0)// Negative numbers count their numbers
ct1++;
else if(i!=++ct2)// If it is a positive integer, find it from the beginning , What does not match is the missing value
return ct2;
}
return n-ct1+1;
}
};
Time complexity :O(n log 2 \log_2 log2n), Sort
Spatial complexity :O(1)
Method four : Two points search
class Solution {
public:
int binarysearch(vector<int>&v,int target){
// Binary search in a given interval
int l=0,r=v.size()-1;
while(l<=r){
int mid=l+(r-l)/2;
if(v[mid]==target)
return mid;
else if(v[mid]<target)
l=mid+1;
else
r=mid-1;
}
return -1;
}
int minNumberDisappeared(vector<int>& nums) {
int n=nums.size();
sort(nums.begin(),nums.end());// Sort
for(int i=1;i<=n;i++){
// Yes 1~n All elements use binary search in turn
if(binarysearch(nums,i)==-1)return i;// The number of occurrences of the description that cannot be found is 1
}
return n+1;// If from 1 To traverse n, this n All positive integers exist , Then positive integer n+1 It must not exist
}
};
Time complexity :O(n log 2 \log_2 log2n), Sort
Spatial complexity :O(1)
Two 、 Sum of three numbers
Solution 1 : Violence law
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int>>result;
int n=num.size();
if(n<3)
return result;
sort(num.begin(),num.end());// Make the result ascending
for(int i=0;i<n-2;i++)
{
if(i&&num[i]==num[i-1])// If the current number of the loop is the same as before continue
continue;
for(int j=i+1;j<n;j++)// Do not repeat the current number +1
{
if(j>i+1&&num[j]==num[j-1])
continue;
for(int k=j+1;k<n;k++)
{
if(k>j+1&&num[k]==num[k-1])
continue;
if(num[i]+num[j]+num[k]==0)
result.push_back({
num[i],num[j],num[k]});
}
}
}
return result;
}
};
Time complexity :O(n log 2 \log_2 log2n) +O(n^3); Sorting algorithm O(n log 2 \log_2 log2n)+ Triple loop enumeration
Spatial complexity :O(1); Array storage and reading data
Solution 2 : Double pointer ( recommend )
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int>>result;
int n=num.size();
if(n<3)
return result;
sort(num.begin(),num.end());
for(int i=0;i<n-2;i++)
{
if(i&&num[i]==num[i-1])
continue;
int l=i+1,r=n-1;
while(l<r)
{
if(num[l]+num[r]+num[i]==0)// If pointer l,r Add the previous number i be equal to 0, Then find the answer
{
result.push_back({
num[i],num[l],num[r]});
while(num[l]==num[l+1]&&l+1<r)// Judge whether the pointer points to repetition , Repeat skip
l++;
while(num[r]==num[r-1]&&r-1>l)
r--;
l++,r--;
}
else if(num[l]+num[r]+num[i]>0)// more , Reduce the right interval
r--;
else// Conversely, reduce the left interval
l++;
}
}
return result;
}
};
Time complexity :O(n log 2 \log_2 log2n) + O(n^2), Sorting algorithm O(n log 2 \log_2 log2n)+ Double pointer
Spatial complexity :O(1)
边栏推荐
猜你喜欢

Rust:axum learning notes (1) Hello World

How CentOS installs mysqldump

Head detached from origin/... Causes push failure

Principle of bean validation --07
![Shell中的文本处理工具、cut [选项参数] filename 说明:默认分隔符是制表符、awk [选项参数] ‘/pattern1/{action1}filename 、awk 的内置变量](/img/ed/941276a15d1c4ab67d397fb3286022.png)
Shell中的文本处理工具、cut [选项参数] filename 说明:默认分隔符是制表符、awk [选项参数] ‘/pattern1/{action1}filename 、awk 的内置变量

The difference between ArrayList and LinkedList

F - Pre-order and In-order(Atcoder 255)

Navicat exports Mysql to table structure and field description

Easy to use shell shortcuts

Prometheus Node Exporter 常用监控指标
随机推荐
Database leader Wang Shan: strive for innovation and carefully Polish high-quality database products
哈希表刷题(下)
Wechat input component adds a clear icon, and clicking clear does not take effect
tcp协议知识详解
Okaleido ecological core equity Oka, all in fusion mining mode
Easy to use shell shortcuts
数据分析师岗位分析
匿名命名管道, 共享内存的进程间通信理解与使用
2022杭电多校联赛第三场 题解
Playwright web crawler actual battle case sharing
Word/excel has a fixed table size. When filling in the content, the table does not change with the cell content
微信小程序轮播图
Rust:axum学习笔记(1) hello world
There are two solutions for the feign call header of microservices to be discarded (with source code)
The project parameters are made into configurable items, and the @configurationproperties annotation is used
Eureka service registry
标准C语言13
ASP语音通知接口对接demo
ISG index shows that the it and business service market in the Asia Pacific region fell sharply in the second quarter
Head detached from origin/... Causes push failure