数组元素的目标和

数组元素的目标和

在这里插入图片描述
在这里插入图片描述
定义两个指针,因为序列有序,所以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
*/

待大宝贝批阅…

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值