• 2016.07.13-vector<vector<int>>应用2——Two Sum扩展


    收获:

      vector<vector<int> >res,不能直接用res[j].push_back(number),因为res[j]是空的,没有初始化

      可以先定义 vector<int> inNumer, res.push_back(inNumber)即可。

    Two Sum中仅仅找出一组符合的输出即可,我希望将数组中所有符合的组合都输出。

     1 #include "stdafx.h"
     2 #include "vector"
     3 #include "map"
     4 #include "iostream"
     5 #include "unordered_map"        //unordered_map的头文件 
     6 using namespace std;
     7 
     8 class MyClass
     9 {
    10 public:
    11     vector<vector<int> > twoSum(vector<int> &nums, int target)
    12     {
    13         unordered_map<int, int> hash;        //初始化名为hash的hash table,<key,value>均为int型        
    14         int size = nums.size();
    15         vector<vector<int> > res;            //先定义一个vector<vector<int> > 存放所有符合条件的组合
    16         vector<int> inIt;                    //存放每一个符合条件的组合
    17         int j = 0;
    18         for (int i = 0; i < size; i++)
    19         {
    20             int numToFind = target - nums[i];
    21             if (hash.find(numToFind) != hash.end())
    22             {
    23                 inIt.push_back(hash[numToFind]);        //先将每组的数放入到inIt中
    24                   inIt.push_back(i);                    
    25                 res.push_back(inIt);                    //将这个组放入到res中
    26                 inIt.clear();                            //清除每组的值
    27             }
    28             hash[nums[i]] = i;                            //将vector中的值放到map中
    29         }
    30         return res;
    31     } 
    32 };
    33 
    34 int _tmain(int argc, _TCHAR* argv[])
    35 {
    36     vector<int> nums = { 1, 2, 3, 4, 4, 9, 8, 10 };
    37     int target = 5;
    38     vector<vector<int> > res;    
    39     MyClass solution;
    40     res = solution.twoSum(nums, target);
    41     int size = res.size();
    42     for (int i = 0; i < size; i++)
    43     {
    44         int vsize = res[i].size();
    45         cout << "[";
    46         for (int j = 0; j < vsize; j++)
    47         {
    48             cout << res[i][j] << " ";
    49         }
    50         cout << "]";
    51     }
    52     cout << endl;
    53     system("pause");
    54     return 0;
    55 }
  • 相关阅读:
    Code samples from Microsoft (AllInOne Code Framework) 微软一站式示例代码库
    spring bean属性property、ref使用方式(转载)
    spring 注入原理
    jQuery LigerUI 插件介绍及使用之ligerGrid
    spring小例子
    spring依赖注入原理
    SpringMVC关键问题讲解
    修改SVN的IP地址
    SpringMVC入门实例及详细讲解
    jQuery LigerUI使用教程入门篇
  • 原文地址:https://www.cnblogs.com/zhuzhu2016/p/5665898.html
Copyright © 2020-2023  润新知