給你乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
給定陣列 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[ [-1, 0, 1],
[-1, -1, 2]
]
這題一看我以為是兩數之和的翻版,不過hash我怎麼也用不上.難受
暴力解法就是三重迴圈+去重
def
threesum
(nums)
: result =
for i in
range
(len
(nums)-2
):a = nums[i]
for j in
range
(len
(nums)
-i-1):
b = nums[j+i+1]
for x in
range
(len
(nums)
-i-j-2)
: c = nums[i+j+x+2]
if a+b+c ==0:
temp =
temp.sort(
)if temp not
in result:
return result
先排序(太重要了)
固定乙個的話其實還是三重迴圈,關鍵在於雙指標一左一右向中間逼近
左指標的移動邏輯是順序移動,重複的直接跳過.
右指標的移動邏輯(很重要)是abc求和,求和的結果大於0,右指標就左移一位.為啥呢?有序陣列你往左移動一位才能減小嘛
def
threesum2
(nums):if
len(nums)
<3:
return
nums.sort(
) result =
if nums[0]
>0:
return result
for index_a in
range
(len
(nums)):
if index_a >
0and nums[index_a]
== nums[index_a-1]
:continue
target =
0- nums[index_a]
index_c =
len(nums)-1
for index_b in
range
(index_a+1,
len(nums)):
if index_b > index_a +
1and nums[index_b]
== nums[index_b -1]
:continue
while index_b < index_c and nums[index_b]
+ nums[index_c]
> target:
index_c -=
1if index_b == index_c:
break
if nums[index_b]
+ nums[index_c]
== target:
[nums[index_a]
, nums[index_b]
, nums[index_c]])
return result
今天沒學到啥
leetcode之15三數之和Golang
題目的要求有兩個,首先是三個數的和為0,其次是這種和為0的三元組不能重複。當給定乙個陣列,我們求滿足和為0的三元組的時候核心思想使用的是暴力破解,也就是三重迴圈,遍歷三次陣列,但是在這裡我們給出如下優化 首先將陣列按照從小到大的順序排序 設定三個指標index,分別為i,j,k,他們分別代表陣列中滿...
15 三數之和 leetcode
給定乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。我一拿到這題,就想著暴力破解,三重迴圈,i答案思路 雙指標法,用雙重迴圈,其中一層迴圈雙指標,乙個迴圈兩個變數,時間複雜度就減少了。第一層固定元素k,第二...
LeetCode 15 三數之和
15.給定乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。注意 答案中不可以包含重複的三元組 方法一,個人解法正確,但是效率太低,時間複雜度o n 3 時間超時,無法提交至leetcode public s...