zoukankan      html  css  js  c++  java
  • Two Sum_Leetcode

    1. Two Sum

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    这题要求返回的是Index且nums并不是sort好的,诸如双指针等方法便无法很好的使用

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dic = {} #1.创建一个空字典
            for i in range(len(nums)):
                if nums[i] in dic: #3.如果,当前值在dic(的keys里)里出现过,(找到2里所说的x了!)则其与记录的index对应的元素 合正好为target
                    return [dic[nums[i]], i]
                else: #2.解题核心:将当前元素与目标相减,得出的差值以key的形式记录进字典里,其val为当前的index(解释为,需要与x相加才能合为target)
                    dic[target - nums[i]] = i


  • 相关阅读:
    Recyclerview设置间距
    Python-socket / socketserver
    服务器存储空间不足,无法处理此命令
    gitbucket
    一些好用的Linux命令组合
    Python socket模块
    用Python在局域网根据IP地址查找计算机名
    thinkpad开机引导方式变成PCI LAN选项解决
    ipython安装
    python xml
  • 原文地址:https://www.cnblogs.com/phinza/p/9944514.html
Copyright © 2011-2022 走看看