鱼C论坛

 找回密码
 立即注册
查看: 1589|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】1. Two Sum #Easy #C

[复制链接]
发表于 2021-4-7 03:30:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Judie 于 2023-6-4 22:01 编辑

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]


Constraints:
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.


因为不理解returnSize是什么 这题我卡了好久qwq
unknown.png

Judy
Python hash table!
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i, x in enumerate(nums):
            if target - x in d:
                return [d[target-x], i]
            else:
                d[x] = i

Sol1
Python slightly better than mine
https://leetcode.com/problems/tw ... lution-in-o-n-time/
class Solution(object):
        def twoSum(self, nums, target):
                buffer_dictionary = {}
                for i in rangenums.__len()):
                        if nums[i] in buffer_dictionary:
                                return [buffer_dictionary[nums[i]], i] #if a number shows up in the dictionary already that means the 
                                                                                                                #necesarry pair has been iterated on previously
                        else: # else is entirely optional
                                buffer_dictionary[target - nums[i]] = i 
                                # we insert the required number to pair with should it exist later in the list of numbers

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-22 09:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表