风雨雾凇 风雨雾凇
首页
  • 服务端

    • golang
  • 其他

    • leetcode
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

风雨雾凇

技术小渣渣
首页
  • 服务端

    • golang
  • 其他

    • leetcode
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • golang

  • 技术文档

  • GitHub技巧

  • Nodejs

  • 博客搭建

  • leetcode

    • 两数之和-1
      • 思路
      • 代码
    • 无重复字符的最长子串-3
    • 整数翻转-7
    • 回文数-9
    • 13-罗马数字转整数
    • 最长公共前缀
    • 3Sum
    • Valid Parentheses
    • Merge Two Sorted Lists
    • Remove Duplicates from Sorted Array
    • Remove Element
    • Implement strStr()
    • Search Insert Position
    • Count and Say
    • 字符串相乘
    • Maximum Subarray
    • Length of Last Word
    • Plus One
    • Add Binary
    • Sqrt(x)
    • 翻转字符串里的单词
    • 字符串的排列
  • 机器学习

  • 技术
  • leetcode
风雨雾凇
2019-12-09
目录

两数之和-1

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例1:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]
1
2
3
4
5

题目地址:两数之和 (opens new window)


# 思路

基于数组建立value-index 的hash表, 循环遍历判断 hashmap[target - num] 是否存在即可。

# 代码

package easy

import (
	"fmt"
	"testing"
)

func twoSum(nums []int, target int) []int {
	// 以 value, index 建立哈希表
	// 初始化时建立可避免重复值问题 如 [3, 3] 6
	hashMap := make(map[int]int)
	// 循环哈希表查看是否存在对应索引
	for index, value := range nums {
		otherKey := target - value
		if otherIndex, has := hashMap[otherKey]; has {
			return []int{otherIndex, index}
		}
		hashMap[value] = index
	}
	return []int{}
}

func Test_main(t *testing.T) {

	fmt.Printf("%v\n", twoSum([]int{3, 3}, 6))
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
编辑 (opens new window)
#leetcode#每日训练#算法#面试#学习笔记
上次更新: 2023/02/17, 16:53:03
vdoing主题效果图
无重复字符的最长子串-3

← vdoing主题效果图 无重复字符的最长子串-3→

最近更新
01
builtin
02-12
02
导读
02-12
03
13-罗马数字转整数
01-30
更多文章>
Theme by Vdoing | Copyright © 2017-2023 风雨雾凇 | 粤ICP备16018321号-2
博客内容遵循署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式