Python 3 LeetCode三数の和
1272 ワード
大体の考え方:元のデータを並べ替えて、それから値は負数の部分で循環して、同じ価値を除去する時順番を並べたため、同じ値はすべていっしょにいて、比較的に便利に同じ値を除去します.注意3つの数は、同じ値があるかどうかを判断する必要があります.
# -*- coding :UTF-8 -*-
class Solution:
def threeSum(self, nums):
result = []
temp_nums = sorted(nums)
l = len(temp_nums)
for i in range(l - 2):
if i > 0 and temp_nums[i] == temp_nums[i -1]:
continue
else:
if temp_nums[i] <= 0:#
j = i + 1
k = l - 1
while j < k:
x = temp_nums[i] + temp_nums[j] + temp_nums[k]
if x == 0:
while j < k and temp_nums[j] == temp_nums[j+1]:#
j += 1
while j < k and temp_nums[k] == temp_nums[k-1]:#
k -= 1
result.append((temp_nums[i], temp_nums[j], temp_nums[k]))
j += 1
elif x > 0:
k -= 1
else:
j += 1
else:
break
return result