力扣——两数之和(暴力法,双指针、哈希表)

40 阅读1分钟

暴力法:

class Solution(object):
    def twoSum(self, nums, target):
        lst = []
        #判断是否相加后为target
        for i in range(len(nums)):
            for j in range(len(nums)):
                if nums[i] + nums[j] == target and i != j:
                    lst.append(j)
                    lst.append(i)
                    return lst
                    # break

# 案例一
nums = [2, 7, 11, 15]
target = 9
sol = Solution()
result = sol.twoSum(nums, target)
print(result)

双指针:

class Solution(object):

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        new_nums = nums[:]
        new_nums.sort()  # 关键:先排序

        left = 0
        right = len(new_nums) - 1

        while left < right:
            current_sum = new_nums[left] + new_nums[right]
            if current_sum == target :
                i = nums.index(new_nums[left])
            # print(nums[0])
                j = nums.index(new_nums[right])
            # print(nums[2])
                if i != j:
                    return [i, j]  # 找到解
            elif current_sum < target:
                left += 1  # 总和太小,左指针右移
            else:
                right -= 1  # 总和太大,右指针左移
        return []  # 无解
 

哈希表:

from typing import List


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 创建一个空字典,用于存储数字及其索引
        num_dict = {}

        # 遍历数组,i是索引,num是当前数字
        for i, num in enumerate(nums):
            # 计算需要的补数(target - 当前数字)
            complement = target - num

            # 如果补数已经在字典中,直接返回结果
            if complement in num_dict:
                return [num_dict[complement], i]  # 返回补数的索引和当前索引

            # 否则将当前数字及其索引存入字典
            num_dict[num] = i

        # 如果没有找到解,返回空列表(题目保证有解,此步可省略)
        return []