第一题:
#给定一个无序数组nums和一个目标值target,返回数组中两个元素的和为target的算法,时间复杂度为O(1);
def func1(nums,target):
dict1 = {}
for i in range(len(nums)):
num = target - nums[i]
if num not in dict1:
dict1[nums[i]] = i
else:
return (dict1[num],i)
===================================
//给定一个整数数组 nums 和一个整数目标值 target,请在该数组中找 和为目标值 target 的三个整数,并返回它们的数组下标?
方法1:
class Foo(object):
@staticmethod
def sum(nums, target):
result = []
n = len(nums)
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
num = nums[i] + nums[j] +nums[k]
if num == target:
result.append(i)
result.append(j)
result.append(k)
break
return result
n = [5,1,2,4]
print(Foo.sum(n,7))
方法2:
可以用列表推导式
nums = [1,2,3,4,5,6,7,8,9]
target=9
list1 = [(x,y,z) for x,x1 in enumerate(nums) for y,y1 in enumerate(nums) for z,z1 in enumerate(nums) if x1!=y1!=z1 and x1+y1+z1==9]
print(list1)
方法3:
def func1(nums,target):
i = 0
while i < len(nums)-2:
j = i+1
k = len(nums)-1
while j < k:
if nums[i]+nums[j]+nums[k] > target:
k -= 1
elif nums[i] + nums[j] + nums[k] < target:
j += 1
else:
return [i,j,k]
i += 1
nums = [1,2,2,3,5]
a = func1(nums,7)