C++ 3sum complexity

前端 未结 4 1182
臣服心动
臣服心动 2021-01-24 19:57

I was trying to solve the 3 sum problem in cpp.

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the

4条回答
  •  情歌与酒
    2021-01-24 20:17

    You can be in O(n²) with something like:

    std::vector> threeSum(std::vector& nums) {
        std::sort(nums.begin(), nums.end());
    
        std::vector> res;
        for (auto it = nums.begin(); it != nums.end(); ++it) {
            auto left = it + 1;
            auto right = nums.rbegin();
            while (left < right.base()) {
                auto sum = *it + *left + *right;
                if (sum < 0) {
                    ++left;   
                } else if (sum > 0) {
                    ++right;   
                } else {
                    res.push_back({*it, *left, *right});
                    std::cout << *it << " " <<  *left << " " << *right << std::endl;
                    ++left;
                    ++right;
                }
            }
        }
        return res;
    }
    

    Demo

    I let duplicate handling as exercise.

提交回复
热议问题