01.两数之和

简介: 01.两数之和

python3

# 解法一:暴力解法
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result = []
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if target == nums[i] + nums[j]:
                    result.append(i)
                    result.append(j)
        return result
     
 
# 解法二:哈希map
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result = {}
        for index, value in enumerate(nums):
            if result.get(target-value) is not None:
                return [index, result.get(target-value)]
            result[value] = index
        return result
       
# 注:enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。


Go

解法一:
func twoSum(nums []int, target int) []int {
    for i := 0;i<len(nums);i++ {
        for j:=i+1;j<len(nums);j++ {
            if target == nums[i] + nums[j] {
                return []int{i,j}
            }
        }
    }
    return nil
}
时间复杂度:O(N^2)

解法二:
func twoSum(nums []int, target int) []int {
    hashmap := map[int]int{}
    for index, value := range nums {
        if p, ok := hashmap[target-value]; ok {
            return []int{index,p}
        }
        hashmap[value] = index
    }
    return nil
}

image.png


目录
相关文章
|
2月前
|
算法
LeetCode第29题两数相除
这篇文章介绍了LeetCode第29题"两数相除"的解题方法,通过使用加法、减法和二进制位移法代替常规的乘除操作,并考虑了整数溢出问题,提供了一种高效的算法解决方案。
LeetCode第29题两数相除
|
2月前
|
算法
LeetCode第2题两数相加
该文章介绍了 LeetCode 第 2 题两数相加的解法,通过同时遍历两个链表的头节点,创建新链表接收计算结果,时间复杂度为 O(n)。
LeetCode第2题两数相加
|
4月前
1.两数之和
1.两数之和
|
5月前
leetcode-29:两数相除
leetcode-29:两数相除
35 0
|
5月前
|
存储
leetcode-2:两数相加
leetcode-2:两数相加
36 0
|
存储 算法
LeetCode2-两数相加
LeetCode2-两数相加
|
存储 算法 安全
LeetCode - #29 两数相除
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。