LeetCode 练习
题15:3SUM
要求求得一个list中任意三个数的组合,对这三个数的要求是加起来和为0
我的思路没什么创新,就是遍历找三个不同数的组合,然后相加判断是否等于0,最后对整个list排序,并剔除重复项,返回new。希望以后能找到更简便的方法。
代码如下:
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
new = []
l = len(nums)
for i in range(l):
for j in range(l):
if i!=j and nums[i]+nums[j] !=0 :
add = nums[i]+nums[j]
for r in range(l):
if r != i and r !=j:
add1 =add+nums[r]
if add1 == 0:
res.append([nums[i],nums[j],
nums[r]])
for k in res:
k.sort()
new.append(res[0])
for k in res:
if k not in new:
new.append(k)
return new
nums=[1,0,-1,1,2,-3]
s = Solution()
print(s.threeSum(nums))
运行结果如下:
题355:求两个集合的交集
这对于python编程来说相对比较容易,就是判断一个是否在另一个集合中是否出现,并且出现的次数是怎样的。
代码如下:
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res=[]
for k in nums1:
if k in res:
continue
for j in nums2:
if j in res:
continue
if j == k :
l1 = len([i for i in range(len(nums1))
if nums1[i] == j])
l2 = len([i for i in range(len(nums2))
if nums2[i] == j])
for n in range(min(l1,l2)): # 如果相同的数在两个集合中的数量一样,就返回这个数量的数值,若不一样,返回最小数量的值
res.append(j)
return res
nums1 = [1,1,2,3,4]
nums2 = [1,1,2,3]
s=Solution()
print(s.intersect(nums1,nums2))
结果如下: