> 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/16.-3sum-closest.md).

# 16. 3Sum Closest

## 1.問題

![](/files/-LLxM27wV2A_o36i1Q85)

## 2.想法

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

## **3.程式碼**

```
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        vector<vector<int>> res;
        int size = nums.size();
        if (size < 3) {
            return 0;
        }
        int value = INT_MAX, minSum = -1;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < size; i++) {
            int j = i + 1;
            int k = size - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                int diff = sum - target;
                if (diff == 0){
                    return sum;
                } else if (diff > 0) {
                    k--;
                } else {
                    j++;
                }
                
                if (abs(diff) < value) {
                    value = abs(diff);
                    minSum = sum;
                }
            }
        }
        
        return minSum;
    }
};
```


---

# 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/16.-3sum-closest.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.
