zoukankan      html  css  js  c++  java
  • ACM_四数之和

    四数之和

    Time Limit: 2000/1000ms (Java/Others)

    Problem Description:

    有n个不同的整数,判断能否从中选4次,4个数和刚好为m。数字可重复选取

    Input:

    输入包含多组测试,每组测试第一行是两个数n(1<=n<=1000)和m(0<=m<=10^9)。
    第二行是n个数a1,a2,a3...an(0<=ai<=10^8);

    Output:

    对于每组测试,如果能从中找出4个数和为m,则输出YES,否则输出NO。

    Sample Input:

    5 10
    1 2 3 4 5
    3 10
    1 3 5
    3 9
    1 3 5

    Sample Output:

    YES
    YES
    NO
    解题思路:因为四数和中选取的每个数字可以重复,因此我们可以先将每每两个数的和存放到set容器中(注意元素具有唯一性即不重复性),然后使用find()来查找set中是否有m-*it这个元素即可,思路清晰,代码可以过,不超时!忽略系数,此解法时间复杂度是O(n^2)。
    AC代码:
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 int a[1005],n,m;
     4 set<int> t;
     5 bool findt(int obj){  //find()返回迭代器在容器中的位置
     6     return t.find(obj)==t.end();
     7 }
     8 int main()
     9 {
    10     while(cin>>n>>m){
    11         t.clear();
    12         for(int i=0;i<n;++i)
    13             cin>>a[i];
    14         for(int i=0;i<n;++i)
    15             for(int j=0;j<n;++j)
    16                 t.insert(a[i]+a[j]);  //每每两个数相加
    17         bool flag=false;  //标记set中是否有这个元素
    18         for(set<int>::iterator it=t.begin();it!=t.end();++it)
    19             if(!findt(m-*it)){flag=true;break;}
    20         if(flag)cout<<"YES"<<endl;
    21         else cout<<"NO"<<endl;
    22     }
    23     return 0;
    24 }
  • 相关阅读:
    leetcode[164] Maximum Gap
    leetcode[162] Find Peak Element
    leetcode[160] Intersection of Two Linked Lists
    leetcode[156] binary tree upside down
    leetcode[155] Min Stack
    leetcode Find Minimum in Rotated Sorted Array II
    leetcode Find Minimum in Rotated Sorted Array
    leetcode Maximum Product Subarray
    ROP
    windbg bp condition
  • 原文地址:https://www.cnblogs.com/acgoto/p/9011174.html
Copyright © 2011-2022 走看看