首页 > 其他分享 >LeetCode-1 Two Sum

LeetCode-1 Two Sum

时间:2024-03-27 23:12:08浏览次数:23  
标签:return hashmap nums int Sum Two complement LeetCode target

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]
Explanation: 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 <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

 

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

Solutions:

a.Brute force solution:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if (nums[i] + nums[j]) == target:
                    return [i,j] 
        

b. Using HashMap

class Solution:
    # This function finds two numbers in the 'nums' list that add up to the 'target' value.
    # It returns a list containing the indices of the two numbers.
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Initialize an empty hashmap to store the values and their corresponding indices
        hashmap = {}  
    
        # Iterate through the 'nums' list using indices
        for i in range(len(nums)):  
            # Calculate the complement of the current number
            complement = target - nums[i]  
            
            # If the complement exists in the hashmap
            if complement in hashmap:  
                # Return the indices of the complement and the current number
                return [hashmap[complement], i]  
            
            # Add the current number and its index to the hashmap
            hashmap[nums[i]] = i  

标签:return,hashmap,nums,int,Sum,Two,complement,LeetCode,target
From: https://www.cnblogs.com/millionyh/p/18100534

相关文章

  • LeetCode-9 Palindrome Number
    9.PalindromeNumber easyGivenaninteger x,return true if x isa palindrome ,and false otherwise. Example1:Input:x=121Output:trueExplanation:121readsas121fromlefttorightandfromrighttoleft.Example2:Input:x=-......
  • LeetCode-21 Merge Two Sorted Lists
    21.MergeTwoSortedLists EasyYouaregiventheheadsoftwosortedlinkedlists list1 and list2.Mergethetwolistsintoone sorted list.Thelistshouldbemadebysplicingtogetherthenodesofthefirsttwolists.Return theheadofthemerg......
  • 【力扣】36. 有效的数独 - 力扣(LeetCode)
    这里主要是记录一些我做这个题遇到的问题及解决办法目录1.问题描述1.1思路分析:2.程序代码及注释:1.问题描述1.1思路分析:  对于个题目而言,我只使用了一个参数,其中我的主要思路就是暴力循环求解,总体思路就是先判断每行是否符合要求,在判断每列是否符合要求、然后......
  • Leetcode 回文链表
    Day12第一题用数组存储链表的数值,在检测是否是回文数组,数组长度不可变,所以用listclassSolution{publicbooleanisPalindrome(ListNodehead){List<Integer>list=newArrayList<>();while(head!=null){list.add(head.val);......
  • leetcode-75
    给定一个包含红色、白色和蓝色、共n个元素的数组nums,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。我们使用整数0、1和2分别表示红色、白色和蓝色。必须在不使用库内置的sort函数的情况下解决这个问题。示例1:输入:nums=[2,0,2,1,1,......
  • LeetCodeHot100 链表 160. 相交链表 206. 反转链表 234. 回文链表 141. 环形链表
    160.相交链表https://leetcode.cn/problems/intersection-of-two-linked-lists/description/?envType=study-plan-v2&envId=top-100-likedpublicListNodegetIntersectionNode(ListNodeheadA,ListNodeheadB){intlenA=0;intlenB=0;L......
  • leetcode.py
    importrequestsimportbase64importtimedefget_img_res():img=""start_time=time.time()withopen('img1.png','rb')asimage_file:#将图片内容转换为base64编码base64_image=base64.b64encode(image_file.rea......
  • Leetcode 翻转二叉树
    Day11第三题目前ac最快的一道题/***Definitionforabinarytreenode.*publicclassTreeNode{*intval;*TreeNodeleft;*TreeNoderight;*TreeNode(){}*TreeNode(intval){this.val=val;}*TreeNode(intval,TreeNo......
  • 论文解读(ACDNE)《Adversarial Deep Network Embedding for Cross-Network Node Classif
    Note:[wechat:Y466551|可加勿骚扰,付费咨询]论文信息论文标题:AdversarialDeepNetworkEmbeddingforCross-NetworkNodeClassification论文作者:XiaoShen、QuanyuDai、Fu-laiChung、WeiLu、Kup-SzeChoi论文来源:2020 AAAI论文地址:download 论文代码:download视屏讲解:c......
  • Leetcode 二叉树的最大深度
    Day11第二题深度优先搜索在计算当前二叉树的最大深度时,可以先递归计算出其左子树和右子树的最大深度,然后在\(\mathcal{O}(1)\)时间内计算出当前二叉树的最大深度。classSolution{publicintmaxDepth(TreeNoderoot){if(root==null){retur......