【每日一题0621】两数之和

题目:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
补充说明:
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]

本题来源:力扣(LeetCode),题目链接:https://leetcode-cn.com/problems/two-sum

1 Like
def twoSum(nums, target):
    length = len(nums)
    for i in range(length):
        try:
            other = nums.index(target - nums[i], i + 1)
        except ValueError as e:
            continue
        return [i, other]

nums = [20, 30, 65, 48, 98]

def find_num_by_target(target: int):
for i in range(len(nums)):
for j in range(i + 1, len(nums) - 1):
if nums[i] + nums[j] == target:
return “两个目标值为:%s的下标为:%s, %s的下标为:%s” % (nums[i], i, nums[j], j)
else:
return “不存在数值和为%s的数字” % target

func = find_num_by_target(95)

print(func)

def get_index(nums, target):
    newnums = []
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] + nums[j] == target:
                newnums.append(i)
                newnums.append(j)
    if len(newnums) == 0:
        print(f"{nums}中没有和为{target}的两个整数")
    else:
        print(f"下标为{newnums}")

nums = [2, 7, 11, 18]
target = 9
get_index(nums, target)

def getindex(nums,target):
for i in range(len(nums)):
j = target -nums[i]
if j in nums and j != i:
return i,nums.index(j)

手机上打的,格式可能不对

第二个for循环不对吧

def two_sum(test_list, target):
    def yield_list():
        for i in range(len(test_list)):
            for j in range(i + 1, len(test_list)):
                if test_list[i] + test_list[j] == target:
                    yield i, j

    return list(yield_list())


assert two_sum([1, 2, 3, 4, 5], 3) == [(0, 1)]
assert two_sum([1, 2, 3, 4, 5], 9) == [(3, 4)]
assert two_sum([1, 2, 3, 4, 5], 5) == [(0, 3), (1, 2)]

题解1:使用enumerate遍历

def find(nums:list, target:int):
    return [i for i, item in enumerate(nums) if target - item in nums[:i]+nums[i+1:]]

assert find([2,7,11,15], 9) == [0, 1]
assert find([3,2,4], 6) == [1, 2]
assert find([3,3], 6) == [0, 1]

题解2:利用组合生成器

import itertools

def get_index(nums,target):
    combs = list(itertools.combinations(nums, 2))
    pairs = [(x,y) for x,y in combs if x+y==target]
    return [i for i,item in enumerate(nums) if item in pairs[0]]


assert get_index([2,7,11,15], 9) == [0,1]
assert get_index([3,2,4], 6) == [1, 2]
assert get_index([3,3], 6) == [0, 1]

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

优秀! :clap: :clap: :clap:

顺便提下,题目中有2处需要关注一下哈:
1.对于输入,补充说明中提到:你可以假设每种输入只会对应一个答案。感觉[(0, 3), (1, 2)]这种的输入可以暂不考虑。当然考虑到了这个场景是值得称赞:+1:
2.输出的格式要求是[0,1],希望能够锦上添花哈。

优秀啊,也是很拼的同学,牛:+1:
总体思路完全正确,就2个小细节可以参考下:

  1. return [i,nums.index(j)] 这里建议改造下,这样就能满足题目输出的要求了,返回一个列表;
  2. 可以再考虑下 输入:nums = [3,3], target = 6 ,预期输出:[0,1]这种用例场景哈。目前的代码实际返回[0,0]了。
    更多用例,可以参阅leetcode原文哈。
def find():
    """ 获取两个数值之和,返回下标"""
    nums = [2, 7, 7, 15]
    target = 9
    for i in range(len(nums)):
        try:
            end = nums.index(target - nums[i], i+1)   #必须指明查询起点,否则有可能返回自身
        except Exception as e:
            return '不存在'
        return [i, end]
	int target=9;
	int[] arry = {2,5,10,7};
	for(int i=0;i<arry.length-1;i++) {
		for(int j=i+1;j<arry.length;j++) {
			if(arry[i]+arry[j]==target) {
				System.err.println(i+"&"+j);
				i=arry.length;
				break;
			}
		}
	}
def get_target(nums,target):
    result=[]
    for i, row in enumerate(nums):
        for j in range(i+1, len(nums)):
            if row + nums[j] == target:
                # print(i,j)
                result.append([i,j])
                break
    return  result
assert  get_target([2, 7, 11, 15,3,6],9)
def find_1(x,y):
    result = []
    for i in range(len(x)-1):
        for j in range(1,len(x)):
            if x[i]+x[j] == y:
                result.append(i)
                result.append(j)
    if len(result) == 0:
        return '无'
    else:
        return result
assert find_1([1, 2, 3, 4, 5], 9) == [3,4]
assert find_1([1, 2], 3) == [0,1]
assert find_1([1, 2], 4) == '无'
def findData(L:list,target:int):
    L1 = list(enumerate(L))
    result = []
    for i,item in L1:
        if target - item in L[:i]  +L[i+1:]:
            result.append(i)
    return result
关闭