美文网首页
map:1.两数之和

map:1.两数之和

作者: Linrundong | 来源:发表于2019-08-04 18:14 被阅读0次

考点:哈希表

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

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

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func twoSum(nums []int, target int) []int {
    var (
        numMap    = make(map[int]int)
        otherTarNum int
        retList = []int{}
    )

    for listIndex, listNum := range nums {
        otherTarNum = target - listNum

        if mapValue, ok := numMap[otherTarNum]; ok {
            if mapValue != listIndex {
                retList = append(retList, mapValue)
                retList = append(retList, listIndex)

                return retList
            }
        }

        //避免使用相同索引组合,先判断再插入
        numMap[listNum] = listIndex
    }

    return nil
}

func main() {
    var (
        sum_list    string
        num_list     = []int{}
        tar_num     int
    )

    fmt.Println("输入数组:")
    fmt.Scan(&sum_list)
    fmt.Println("输入数字合:")
    fmt.Scan(&tar_num)

    list_str:= strings.Split(sum_list, ",")
    for _, str := range list_str {
        tmp, _ := strconv.Atoi(str)
        num_list = append(num_list, tmp)
    }

    fmt.Println(twoSum(num_list, tar_num))
}

相关文章

  • map:1.两数之和

    考点:哈希表

  • 1. 两数之和

    https://leetcode-cn.com/problems/two-sum/description/给定一个...

  • 1. 两数之和

    内容 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素...

  • 1. 两数之和

    20180919-摘抄自1. 两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每...

  • 1. 两数之和

    1、暴力法,求target-num[current]是否满足 2、哈希表

  • 1. 两数之和

    代码 分析 主要是利用map集合来存储值,存储的是下一下要找的值和当前的索引,然后找到的时候就可以知道这两个索引

  • 1. 两数之和

    一、题目原型: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同...

  • 1.两数之和

    题目: 给定一个整数数列,找出其中和为特定值的那两个数。 你可以假设每个输入都只会有一种答案,同样的元素不能被重用...

  • 1.两数之和

    leetcode算法学习,打算每日1篇 自己写的代码太low就不上了,主要是对最优代码的注释和自己的小小理解 题目...

  • 1. 两数之和

    LeetCode 的算法题 PHP解法记录 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假...

网友评论

      本文标题:map:1.两数之和

      本文链接:https://www.haomeiwen.com/subject/xfbydctx.html