15. 3Sum - Medium
前往題目
照搬一下之前寫的
想法
- 這題很難,覺得應該要是
hard
- 解法不複雜,但想法很有挑戰性
- 先排序是因為這樣
l
和r pointer
的位置就很清楚了,l
往右一定是維持或是sum
變大,r
往左一定是維持或是sum
變小 - 這個解法是$O(N^2)$
思路
- Sort it
- iterate the nums
- Check if duplicate to the previous number (To prevent redundant check)
- using 2 pointer, make the initial number fixed so that the problem turns into 2 sum
- 2 pointers to check the and find sum which is 0
- When update, just update left pointer until it has a different number from the last one (To prevent redundant), right pointer will be handled by existing logics
Code
2024/01/07
- 沒想出來,看了解答的思路後寫出來了
2024/01/30
- 大框架寫出來了但缺了一些細節,這個題目的細節蠻容易忽略的,尤其是可能會遇到重複的該怎麼處理
15. 3Sum - Medium
https://f88083.github.io/2024/01/07/15-3Sum-Medium/