LeetCode Algorithm Practice | LeetCode 算法实践

qq_24247 0 0 zip 2024-10-08 15:10:37

leetcode 2和c leetcode-算法-实践

  1. 二和

给定一个整数数组,返回两个数字的索引,使它们相加为特定目标。您可以假设每个输入将只有一个解决方案,并且您可能不会两次使用相同的元素。

例子:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]。

答:


class Solution:

    def twoSum(self, nums, target):

        length = len(nums)

        for i in range(length):

            num2 = target - nums[i]

            try:

                return [i, nums.index(num2, i+1, length)]

            except ValueError:

                continue

  1. 3和

给定一个由n个整数组成的数组nums,nums中是否有元素a、b、c使得a + b + c = 0?在数组中找到所有唯一的三元组,其总和为零。

注意:解决方案集不得包含重复的三元组。

例子:

用户评论
请输入评论内容
评分:
暂无评论