断了好几天的LeetCode,前两天把一个算法写出来了,本来应该还挺开心的,但又发生了一些事。生活已经很艰难了,希望自己永远坚持做一个以从平常心对待他人的人,永远不要把坏情绪乱发泄在别人身上。我要向光哥看齐!
今天贴两个!我觉得这里是不考虑不包含三个以下的情况的。
3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
Code
其实看了一下discussion的,然后看到用左中右标记就回去自己写了,直接贴代码吧:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
r = set()
nums.sort()
for center in range(1, len(nums) - 1):
left = 0
right = len(nums) - 1
while (left < center) and (right > center):
temp = nums[left] + nums[center] + nums[right]
if (temp == 0):
r.add((nums[left], nums[center], nums[right]))
left += 1
right -= 1
elif (temp < 0):
left += 1
else:
right -= 1
return list(r)
结果:
313 / 313 test cases passed.
Runtime: 1580 ms
Memory Usage: 17 MB
Runtime: 1580 ms, faster than 21.87% of Python3 online submissions for 3Sum.
Memory Usage: 17 MB, less than 25.71% of Python3 online submissions for 3Sum.
3Sum Closest
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Code
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
r = sum(nums[:3])
temp = abs(r - target)
for center in range(1, len(nums)-1):
left = 0
right = len(nums) - 1
while (left < center) and (center < right):
temp1 = nums[left] + nums[center] + nums[right]
if temp1 == target:
return target
if abs(target - temp1) < temp:
temp = abs(target - temp1)
r = temp1
if temp1 < target:
left += 1
else:
right -= 1
return r
结果:
125 / 125 test cases passed.
Runtime: 144 ms
Memory Usage: 14 MB
Runtime: 144 ms, faster than 50.72% of Python3 online submissions for 3Sum Closest.
Memory Usage: 14 MB, less than 5.41% of Python3 online submissions for 3Sum Closest.
生活不易,希望能过上开心的生活!