0x00 问题描述

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].

0x01 问题分析

使用两组循环逐一尝试相加结果是否等于目标值,如果相等返回其索引值。
每个数值只能使用一次,所以需要避免两个数重复项加,所以第二层循环则从当前数字的下一位开始,且不与以经尝试过的数字相加。

0x02 Go代码

func twoSum(nums []int, target int) []int {
    for i := 0; i < len(nums); i++ {
        for j := i+1; j < len(nums); j++ {  //只与其余下的值相加,避免重复操作
            if nums[i] == target - nums[j] {
                temp := []int{i,j}
                return temp
            }
        }
    }
    return []int{0,0}  //若果失败返回0 报错提示需要返回整数数组
}

标签: Golang, LeetCode

评论已关闭