leetcode--two number of the sum (1)

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

1. Given an array of integers and a target value, find the two numbers in the array and the target values.

You can assume that each input corresponds to only one answer, and that the same element cannot be reused.

Example:

Given nums = [2, 7, one, all], target = 9

Because Nums[0] + nums[1] = 2 + 7 = 9
So return [0, 1]

Go implementation:

package mainimport (    "fmt")func main() {    nums := []int{1, 3, 4, 6, 7, 10}    target := 17    newArr := twoSum(nums, target)    fmt.Println(newArr)}func twoSum(nums []int, target int) []int {    maps := make(map[int]int)    for index, value := range nums {        member := target - value        if _, ok := maps[member]; ok {            return []int{member, value}        } else {            maps[value] = index        }    }    return []int{}}

Time complexity O (n);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.