LeetCode 第一题

来源:互联网 发布:手机音乐后期软件 编辑:程序博客网 时间:2024/05/22 04:46

LeetCode 第一题

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

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

第一题很简单,求两个值加起来等于目标值的坐标。

func twoSum(nums []int, target int) []int {    var result []int    for index, x := range nums {        for j := index + 1; j < len(nums); j++ {            if x+nums[j] == target {                result = append(result, index)                result = append(result, j)                break            }        }        if len(result) != 0 {            break        }    }    return result}
原创粉丝点击