LeetCode:Two Sum

Posted strengthen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode: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].


给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

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

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





 1 class Solution {
 2     func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
 3         //创建一个初始化数据为空的数组用于返回
 4         var targetArray:[Int]=[Int]()
 5         //获取数组长度,减2用于遍历数组,注意最后一个的情况
 6         for addIndex1 in 0...nums.count-2
 7         {
 8             //该值之后向后遍历,不支持运算符<..
 9             for addIndex2 in (addIndex1+1)...nums.count-1
10             {
11                 if(nums[addIndex1]+nums[addIndex2]==target)
12                 {
13                     targetArray.append(addIndex1)
14                     targetArray.append(addIndex2)
15                     break                   
16                 }               
17             }
18         }
19         return targetArray
20     }
21 }

 





以上是关于LeetCode:Two Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(371) Sum of Two Integers

Leetcode Two Sum

1_Two Sum --LeetCode

leetcode371. Sum of Two Integers

LeetCode之371. Sum of Two Integers

LeetCode: 371 Sum of Two Integers(easy)