鏈接:
2058. 找出臨界點(diǎn)之間的最小和最大距離
題意:
鏈表
某個(gè)節(jié)點(diǎn)嚴(yán)格大于前后時(shí),這個(gè)節(jié)點(diǎn)為局部極大值節(jié)點(diǎn);某個(gè)節(jié)點(diǎn)嚴(yán)格小于前后時(shí),這個(gè)節(jié)點(diǎn)為局部極小值節(jié)點(diǎn)
前提:必須前后均非空
找兩個(gè)不同臨界點(diǎn)的最大距離和最小距離
解:
一開始還以為要找極大和極小之間的最大最小,后來看了一下案例發(fā)現(xiàn)就是單純的不同臨界點(diǎn)
所以判斷一下是否是臨界點(diǎn),然后存一下上一個(gè)臨界點(diǎn)和第一個(gè)臨界點(diǎn)下標(biāo)就可以了
剩下都是一些基本鏈表操作
實(shí)際代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-554876.html
#include<bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
vector<int> nodesBetweenCriticalPoints(ListNode* head)
{
vector<int> ans {INT_MAX,INT_MIN};
int index_head=INT_MAX,index_pre=0;
int t1=head->val,t2=0,t3=0;
int mao=1;head=head->next;
for(;head->next!=nullptr;mao++)
{
t2=head->val;t3=head->next->val;
//cout<<mao<<":"<<t1<<" "<<t2<<" "<<t3<<endl;
if(t3)//合規(guī)節(jié)點(diǎn)
{
if( (t2<t1 && t2<t3) || (t2>t1 && t2>t3) )//局部極小值點(diǎn) || 局部極大值點(diǎn)
{
if(index_pre)//存在上一個(gè)臨界點(diǎn)
{
ans[0]=min( ans[0] , abs(mao-index_pre) );
}
index_head=min(index_head,mao);
index_pre=mao;
}
}
head=head->next;t1=t2;
}
if(index_head==INT_MAX || index_head==index_pre)//沒有 || 僅一個(gè)
{
ans[0]=ans[1]=-1;
}
else ans[1]=abs(index_pre-index_head);
return ans;
}
int main()
{
ListNode* head=nullptr;
ListNode* thead;
int n;cin>>n;
for(int f=1;f<=n;f++)
{
int temp;cin>>temp;
if(f==1)
{
head=new ListNode(temp);
thead=head;
}
else
{
head->next=new ListNode(temp);
head=head->next;
}
}
vector<int> ans=nodesBetweenCriticalPoints(thead);
for(auto i :ans) cout<<i<<" ";
return 0;
}
限制:文章來源地址http://www.zghlxwxcb.cn/news/detail-554876.html
- 鏈表中節(jié)點(diǎn)的數(shù)量在范圍
[2, 105]
內(nèi) 1 <= Node.val <= 105
到了這里,關(guān)于2023-07-12力扣今日三題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!