V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
GJXxiaoBai
V2EX  ›  Python

求各位大牛帮帮忙,感谢!!!

  •  
  •   GJXxiaoBai · 2018-08-30 15:00:21 +08:00 · 1856 次点击
    这是一个创建于 2065 天前的主题,其中的信息可能已经有所发展或是发生改变。
    一个无序不重复的整数数组, 给一个数值为 k, 求有多少对数之和为 k (两个数相加等于 k ), 有多少对之差为 k
    希望各位大佬能提供代码,谢谢了!!!
    8 条回复    2018-09-01 18:40:28 +08:00
    jiakangzhong
        1
    jiakangzhong  
       2018-08-30 15:31:08 +08:00
    给了估计也看不懂

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    int n;
    long long a[50010],k;
    int main()
    {
    scanf("%lld%d",&k,&n);
    bool temp=false;
    for(int i=1;i<=n;i++)//从第一位开始录入
    scanf("%lld",&a[i]);
    sort(a+1,a+n+1);
    for(int i=1;i<=n;i++){//核心代码
    if((a[i]+a[n])<k)continue;//如果相加小于题定值,退出本次循环
    for(int j=i+1;j<=n&&a[i]+a[j]<=k;j++){
    if(a[i]+a[j]==k){
    temp=true;
    printf("%lld %lld\n",a[i],a[j]);
    }
    }
    }
    if(!temp)printf("No Solution\n");
    return 0;
    raycool
        2
    raycool  
       2018-08-30 15:32:50 +08:00
    leetcode 上的第一题?
    ranoff
        3
    ranoff  
       2018-08-30 15:54:38 +08:00
    给个思路吧:先排序,排序的时候顺便把小于 k 和大于 k 的拆开,然后遍历
    imn1
        4
    imn1  
       2018-08-30 15:58:13 +08:00
    @ranoff
    还有单双,减少遍历次数
    Yourshell
        5
    Yourshell  
       2018-08-30 15:58:47 +08:00 via iPhone
    x=k-list[n], x==list[m]
    感觉就是 leetcode 第一题
    ranoff
        6
    ranoff  
       2018-08-30 16:00:19 +08:00
    @imn1 是的
    imn1
        7
    imn1  
       2018-08-30 16:25:17 +08:00
    如果不考虑优化,py 代码很简单
    pandas
    第一列 = 原始数列
    第二列 = K - 第一列
    第三列 = 第二列 in 第一列 (bool)
    提取第三列为 true 的所有行,并去掉第三列

    求差同理
    EV3
        8
    EV3  
       2018-09-01 18:40:28 +08:00
    是两数之和吗?
    我的解法 https://www.jianshu.com/p/6f92ab0fe509
    就是效率比较感人 执行用时:988 ms 超过 62.31 % 的 python 提交记录

    自学 Python 2 个月 之前没有编程经历 请勿见笑....
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1592 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:02 · PVG 01:02 · LAX 10:02 · JFK 13:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.