leetcode/notes/src/three_sum.md
Sainnhe Park b0abd362d5
All checks were successful
continuous-integration/drone Build is passing
Add three_sum.md
2022-12-03 11:40:33 +08:00

33 lines
1005 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 三数相加
[Leetcode 15. 3Sum](https://leetcode.com/problems/3sum/)
这是一道典型的双指针 + 排序的题目。
如果暴力枚举的话时间复杂度是 O(n^3) ,我们考虑用双指针来遍历。
双指针可以将 O(n^2) 的时间复杂度降到 O(n),如果这道题用了双指针的话可以将时间复杂度降到 O(n^2) 。
思路很简单,首先对数组从小到大排序,然后 `for i from 0 to end` ,这是第一重循环
然后在 [i+1, end] 这个区间里,定义一个 left 从左往右,和一个 right 从右往左。
终止条件是它们相遇,或者三数相加满足题目条件。
当三数之和小于 0 时left 往右移;
当三数之和大于 0 时right 往左移。
---
[Leetcode 18. 4Sum](https://leetcode.com/problems/4sum/)
和三数相加差不多,只不过我们把 `for i from 0 to end` 这个循环改成了双重循环
```text
for i from 0 to end
for j from i+1 to end
```
其它都一样。时间复杂度 O(n^3)