陣列元素的目標和


定義兩個指標,因為序列有序,所以i指標從前往后走,j指標從后往前走,這樣可以避免j指標多次遍歷,減少時間復雜度
編碼方式一:
手動操控i,j 指標的加加減減;除錯多次才成功,
注意:int i=m-1;陳述句要放在scanf("%d",&m);后面,否則給i賦值為0;
#include<bits/stdc++.h>
using namespace std;
#define N 100005
int A[N],B[N],n,m,x;
int main(){
scanf("%d%d%d",&n,&m,&x);
int i=0,j=m-1;
for(int i=0;i<n;i++) scanf("%d",&A[i]);
for(int j=0;j<m;j++) scanf("%d",&B[j]);
while(i<n)
{
while(A[i]+B[j]>x&&j>0){
j--;
}
if(A[i]+B[j]==x) printf("%d %d",i,j);
i++;
}
return 0;
}
代碼方式二:
利用for回圈,代碼簡潔易除錯
#include<bits/stdc++.h>
using namespace std;
#define N 100005
int A[N],B[N],n,m,x;
int main(){
scanf("%d%d%d",&n,&m,&x);
for(int i=0;i<n;i++) scanf("%d",&A[i]);
for(int j=0;j<m;j++) scanf("%d",&B[j]);
for(int i=0,j=m-1;i<n;i++)
{
while(A[i]+B[j]>x) j--;
if(A[i]+B[j]==x)
printf("%d %d",i,j);
}
return 0;
}
/*
4 5 6
1 2 4 7
3 4 6 8 9
*/
待大寶貝批閱…
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/22028.html
標籤:java
上一篇:FFmpeg 踩坑記錄
下一篇:視頻超分:TDAN(TDAN: Temporally Deformable Alignment Network for Video Super-Resolution)
