Finding three elements that sum to K

后端 未结 1 1109
情话喂你
情话喂你 2021-01-29 06:17

I wrote the following to find two elements that sum to K

#include 
#include 

void sum_equal_to_k(int *a, int n, int k) { /*         


        
相关标签:
1条回答
  • 2021-01-29 06:23

    The problem is known as 3SUM. There's an O(n^2) algorithm for solving it that you can find here, that doesn't require any hashing.

    It'll be simpler if you just use vector (you're already using unordered_map anyway, right?):

    void sum3_k(std::vector<int> s, int k) {
        std::sort(s.begin(), s.end());
    
        for (size_t i = 0; i < s.size() - 2; ++i) {
            size_t start = i + 1;
            size_t end = s.size() - 1;
    
            while (start < end) {
                int sum = s[i] + s[start] + s[end];
                if (sum == k) {
                    std::cout << s[i] << " " << s[start] << " " << s[end] << std::endl;
                    ++start, --end;
                }
                else if (sum > k) {
                    --end;
                }
                else {
                    ++start;
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题