LeetCode:Two Sum
阿新 • • 發佈:2018-09-19
ould 支持 註意 add ger two sum not fun 不能
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