0
点赞
收藏
分享

微信扫一扫

刷 LeetCode 从零开始学 GoLang(1):1. Two Sum


题目描述

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

GoLang 语法:for 循环

  1. for 循环的一般形式

for initialization; condition; post{
// do something...
}

  1. (1) 和 C++ 不同的是 GoLang 的 for 循环语句没有小括号
    (2) GoLang 的大括号左边一定要在 ​​​post​​ 后面,不能换行
  2. 类似于 C++ 的 while 循环

for condition {
// do something...
}

  1. 死循环

for {
// do something...
}

  1. for range

for key, value := range container{
// do something with key, value...
}

AC 代码

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] + nums[j] == target{
return []int{i, j}
}
}
}

return []int{-1,-1}
}


举报

相关推荐

0 条评论