> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/15.-3sum-1.md).

# 15. 3Sum

## 1.問題

![](/files/-LLxJuq-OI48P0O48IFh)

## 2.想法

* 提問
* function header, parameter
* test input
* 說明想法
  * 對序列後排序
  * 使用兩個迴圈
  * 分別使用3個指標,  依題意的目的是要總和為0,  因此必須要有正負數
    * i 所指向的必須是負數, 因此若nums\[i] > 0則break
    * 若總和 == 0, 則記錄i, j , k的數值
    * 若總和 < 0, 則表示總和太小, 讓j++
    * 若總和 > 0, 則表示總和太大, 讓k--
* 測試計算複雜度: O(n^2) ?

## **3.程式碼**

```
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& num) {
        vector<vector<int>> res;
        int size = num.size();
        if (size < 3) {
            return res;
        }
        sort(num.begin(), num.end());
        
        for (int i = 0; i < size - 2; i++) {
            int a = num[i];
            if (a > 0) {
                break;
            }
            if (i > 0 && a == num[i -1]){
                continue;
            }
            int j = i + 1;
            int k = size - 1;
            while (j < k) {
                int b = num[j];
                int c = num[k];
                int sum = a + b + c;
                if (sum == 0){
                    res.push_back({a, b, c});
                    while(b == num[++j]);
                    while(c == num[--k]);
                } else if (sum > 0){
                    k--;
                } else {
                    j++;
                }
            }
        }
        return res;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/15.-3sum-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
