You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中将HashSet字符串集合转为二维向量?(LeetCode三数之和场景)

三数之和问题:将集合转换为二维整数向量

针对现有三数之和的实现,我们需要把存储符合条件三元组的unordered_set<string>转换为vector<vector<int>>返回,同时修正原代码中插入空字符串的问题。以下是完整的实现代码:

#include <vector>
#include <algorithm>
#include <unordered_set>
#include <string>
#include <sstream>

using namespace std;

vector<vector<int>> threeSum(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    unordered_set<string> s;
    
    for (int start1 = 0; start1 < nums.size(); start1++) {
        for (int start2 = start1 + 1; start2 < nums.size(); start2++) {
            for (int start3 = start2 + 1; start3 < nums.size(); start3++) {
                string str = "";
                if (nums[start1] + nums[start2] + nums[start3] == 0) {
                    // 用逗号做分隔符,避免数字拼接歧义(比如-1和12不会拼成-112)
                    str += to_string(nums[start1]) + "," +
                           to_string(nums[start2]) + "," +
                           to_string(nums[start3]);
                    s.insert(str);
                }
                // 仅在找到有效三元组时插入集合,避免空字符串混入
            }
        }
    }
    
    // 将集合转换为二维整数向量
    vector<vector<int>> result;
    for (const string& str : s) {
        vector<int> triplet;
        stringstream ss(str);
        string numStr;
        // 按逗号拆分字符串并转换为整数
        while (getline(ss, numStr, ',')) {
            triplet.push_back(stoi(numStr));
        }
        result.push_back(triplet);
    }
    
    return result;
}

关键说明

  1. 修复原代码缺陷:原代码会将空字符串插入集合,现在改为仅在找到和为0的三元组时才插入拼接后的字符串;同时添加逗号分隔符,解决负数与正数拼接时的歧义问题。
  2. 集合转二维向量逻辑:通过stringstream按分隔符拆分每个字符串,再用stoi将子串转为整数,组成三元组后加入结果向量。

内容的提问来源于stack exchange,提问作者Abhisek Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:54:20