首页 > 代码库 > 和为s的两个数字的调试

和为s的两个数字的调试

这是整个调试, for (int i:s) cout<<i<<endl;这句话是c++11特性下的一种遍历方式

在编译的时候需要加-std=c++11,即g++ 41.cpp -std=c++11

如果不加就会报错,因为这是c++11的特性

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        vector<int> result;
        if(array.size() <= 0)
            return result;
        //cout<<array.size()<<endl;
        vector<int>::iterator first = array.begin();
        vector<int>::iterator last = array.end() - 1;
        cout<<*last<<endl;
        while(first < last){
            int number = *first + *last;
            if(number == sum){
                result.push_back(*first);
                result.push_back(*last);
                first++;
                last--;
                cout<<array.size()<<endl;
            }
            else if(number < sum){
                first++;
                cout<<number<<endl;
                cout<<1<<endl;
            }
            else{
                last--;
                cout<<2<<endl;
            }
        }
        if(result.size() > 2){
            cout<<2<<endl;
            return Findsmall(result);
            // return result;
        }
        else{
            cout<<result.size()<<endl;
            return result;
        }
    }
    vector<int> Findsmall(vector<int> array){
        int length = array.size();
        int pair = length/2;
        vector<int> result(2,0);
        int product = 999999;
        for(int i = 0;i < pair;i++){
            int num = array[2*i]*array[2*i+1];
            if(num < product){
                result[0] = array[2*i];
                result[1] = array[2*i+1];
                product = num;
            }
        }
        return result;
    }
};


int main(){
    Solution a;
    int b[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
    vector<int> base(b,b+20);
    vector<int> s = a.FindNumbersWithSum(base,21);
    for (int i:s) cout<<i<<endl;
    return 0;
}

 

和为s的两个数字的调试