美文网首页
LintCode 57-三数之和

LintCode 57-三数之和

作者: 胡哈哈哈 | 来源:发表于2016-05-21 16:59 被阅读42次

分析

注意hash去重

class Solution {
public:    
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    vector<vector<int> > threeSum(vector<int> &nums) {
        // write your code here
        vector<vector<int>> ret;
        unordered_set<long long> d;
        for (int i = 0; i < nums.size() - 2; ++i) {
            int sum = -nums[i];
            unordered_set<int> s;
            for (int j = i + 1; j < nums.size(); ++j) {
                if (s.find(nums[j]) != s.end()) {
                    vector<int> ans;
                    ans.push_back(nums[i]);
                    ans.push_back(nums[j]);
                    ans.push_back(-(nums[i] + nums[j]));
                    sort(ans.begin(), ans.end());
                    long long t = 33 * 33 * ans[0] + 33 * ans[1] + ans[2];
                    if (d.find(t) == d.end()) {
                        ret.push_back(ans);
                        d.insert(t);
                    }
                } else {
                    s.insert(sum - nums[j]);
                }
            }
        }
        return ret;
    }
};

相关文章

  • LintCode 57-三数之和

    分析 注意hash去重

  • lintcode 三数之和

    给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。注意...

  • LintCode三数之和系列问题

    三数之和 LintCode57 三数之和解题思路:先对数组排序,然后开始遍历,对于数组中的每一个元素,用两指针往中...

  • LintCode 57. 三数之和

    原题 解 第一步,万年不变的查错。如果给的array是null或不够三个数,直接return 空的result。因...

  • LintCode 57. 三数之和

    题目描述 给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三...

  • lintcode 两数之和

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。你需要实现的函数twoSum需要返回这两个数...

  • lintcode 四数之和

    给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。注意事项...

  • lintcode 最接近的三数之和

    给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。注意事项只需...

  • LintCode - 两数之和(普通)

    版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:容易 要求: 给一个整数数组,找到两个数使得他们的和等...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

网友评论

      本文标题:LintCode 57-三数之和

      本文链接:https://www.haomeiwen.com/subject/bkhorttx.html