关于c ++

时间:2015-10-02 15:08:14

标签: c++

https://leetcode.com/problems/two-sum/上提出的问题的解决方案:

  

给定一个整数数组,找到两个数字,使它们加起来   特定的目标号码。

     

函数twoSum应该返回两个数字的索引   它们加起来到目标,其中index1必须小于index2。   请注意,您返回的答案(index1和index2)都是   不是从零开始的。

     

您可以假设每个输入都只有一个解决方案。

     

输入:数字= {2,7,11,15},目标= 9输出:index1 = 1,index2 = 2

by wz2326(https://leetcode.com/discuss/58175/clean-16ms-c-solution):

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> hash;
    vector<int> res(2, 0);
    for (int i = 0; i < nums.size(); i++) {
        if (hash.find(target - nums[i]) != hash.end()) {
            res[0] = hash[target - nums[i]], res[1] = i + 1;
            return res;
        }
        hash[nums[i]] = i + 1;
    }
}

在向矢量元素赋值时,引入了相当奇怪的逗号用法:

res[0] = hash[target - nums[i]], res[1] = i + 1;

有人知道逗号的含义吗?感谢。

0 个答案:

没有答案