lizhashi0623
lizhashi0623
2017-04-19 10:33

c++, vector subscript out of range 哪里有问题?

  • c++
  • leetcode
 #include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;


class Solution {
public:
    vector<vector<int>> For4Sum(vector<int> &nums,int target) {
        vector<vector<int>> result;
        unordered_map<int,vector<pair<int,int>>> map;

        sort(nums.begin(), nums.end());

        if (nums.size() < 4) return result;

        for (int i = 0; i < nums.size()-1; i++) {
            for (int j = i + 1; j < nums.size(); i++) {
                map[nums[i]+nums[j]].push_back(pair<int,int>(i,j));
            }
        }

        for (int i = 0; i < nums.size() - 1; i++) {
            for (int j = 0; j < nums.size(); i++) {

                int key = target - nums[i] - nums[j];
                if (map.find(key) != map.end()) {
                    for (int k = 0; k < map[key].size(); k++) {
                        if (i < map[key][k].first) {
                            result.push_back({ nums[i], nums[j], nums[map[key][k].first],nums[map[key][k].second] });
                        }
                    }
                }

            }
        }

        sort(result.begin(), result.end());
        result.erase(unique(result.begin(),result.end()),result.end());

        return result;
    }


};


int main() {

    Solution a;
    vector<int> test;
    int target;
    int temp = 0;
    cout << "input target" << endl;
    cin >> target;

    cout << "input nums" << endl;
    while (cin >> temp) {//ctrl+z  
        test.push_back(temp);
    }


    vector<vector<int>> result; 
    result=a.For4Sum(test, target);

    for (int i = 0; i < result.size(); i++) {
        for (int j = 0; j < result[i].size(); j++)
            cout << result[i][j] << " " << endl;
        cout << endl;
    }


    system("pause");
    return 0;
}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答