找和为K的两个元素

总时间限制:1000ms 内存限制: 65536kB

描述

在一个长度为n(n < 1000)的整数序列中,判断是否存在某两个元素之和为k。

输入

第一行输入序列的长度n和k,用空格分开。

第二行输入序列中的n个整数,用空格分开。

输出

如果存在某两个元素的和为k,则输出yes,否则输出no。

样例输入

9 10
1 2 3 4 5 6 7 8 9

样例输出

yes


ac代码

/*
@File     :   find_element.cpp
@Time     :   2020/03/22 14:51:43
@Contact  :   levarz@163.com 
@Desc     :   找和为K的两个元素
*/
#include <iostream>
#include <stdlib.h>
#define MAX_LEN 1010

using namespace std;
/**
 * @brief 数组读入数据
 * 
 * @param array 数组    
 * @param length 数组长度
 */
void read_data_for(int array[], int length);
/**
 * @brief 查找valu在数组中第一个位置
 * 
 * @param value 查找元素    
 * @param pos 元素value第一次出现的逻辑位置,不存在pos为-1
 * @param array 数组
 * @param length 数组长度
 * @return true 元素存在
 * @return false 元素不存在
 */
bool find_first_of(int value, int &pos, int array[], int length);

int main(int argc, char const *argv[])
{
    int numbers[MAX_LEN], n, k, pos = -1;
    cin >> n >> k;
    read_data_for(numbers,n);
    for (int i = 0; i < n; i++) {
        if (find_first_of(k-numbers[i],pos,numbers,n))
        {
            cout << "yes" <<endl;
            system("pause");
            return 0;
        } 
    }
    cout << "no" <<endl;
    system("pause");
    return 0;
}
void read_data_for(int array[], int length)
{
    for (int i = 0; i < length; i++) {
        cin >> array[i];
    } 
}
bool find_first_of(int value, int &pos, int array[], int length)
{
    for (int i = 0; i < length; i++) {
        if (value == array[i]) {
            pos  = i + 1;
            return true;
        }  
    }
    pos = -1;
    return false;
}
原文地址:https://www.cnblogs.com/levarz/p/12781365.html