标签:for and may index 示例 turn UNC NPU 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 }
标签:for and may index 示例 turn UNC NPU sum
原文地址:https://www.cnblogs.com/strengthen/p/9676533.html