leetcode hot 100-01 两数之和

题目:两数之和

难度:简单

题目地址:https://leetcode.cn/classic/problems/two-sum/description/

过程一,因为难度是简单,就没有仔细审题,以为返回两个数就好,使用双指针,逻辑如下:

    对数组排序

    双指针分别指向头和尾

    两数之和大于target,尾部指针-1

    两数之和大于target,首部指针+1

    两数之和等于target,返回

    首部指针大于等于尾部指针,则返回错误

    代码如下:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        head,tail = 0,len(nums) -1
        nums.sort()
        while head<tail:
            if nums[head] + nums[tail] == target:
                return [head, tail]
            elif nums[head] + nums[tail] < target:
                head += 1
            elif nums[head] + nums[tail] > target:
                tail -= 1
        return[]

    结果就是报错,不符合题意,要求的是返回坐标,排序之后坐标顺序发生了变化

过程二,思考如何快速找到坐标

    假设,如果知道每个数字的坐标

    循环数组

    target - current_num 在数组中,并且不是当前的索引,就可以返回

    如何构建索引:

      1、遍历两次数组,将数字放入索引中

      2、循环一次的同时,构建数组的索引映射关系

    思考:

      第一种比较直观,但是在第二次遍历的时候,需要排除当前索引

      第二种,遍历的过程中构建映射关系,不需要排除索引,也就是没有targ-current_num 在索引映射表中。再把current_numf放入到数组中即可

  

from typing import List


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        temp_dict = {}

        for index,v in enumerate(nums):
          
            if target - v in temp_dict:
                return [index,temp_dict[target-v]]
            else:
                temp_dict[v] = index



        

 总结:

    一定要仔细看题,不能想当然,算法题目,可以先预设已知条件,在已知条件的情况下再看是否能完成推论。如果可以再对已知条件进行推论

    

    

    

    

posted @ 2023-11-12 15:35  soultank  阅读(2)  评论(0编辑  收藏  举报