在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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] 一遍哈希表我们可以一次完成。在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。 Runtime: 32 ms
Memory Usage: 19.3 MB
1 class Solution { 2 func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 var table:[Int:Int] = [Int:Int]() 4 for (firstIndex, num) in nums.enumerated() { 5 var res: Int = target - num 6 //可选链接 7 if let secondIndex = table[res] 8 { 9 return [secondIndex,firstIndex] 10 } 11 else 12 { 13 table[num] = firstIndex 14 } 15 } 16 return [-1,-1] 17 } 18 } 36ms 1 class Solution { 2 func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 var out: [Int] = [] 4 5 var dict:[Int: Int] = [:] 6 for (index,num) in nums.enumerated() { 7 if let sum = dict[target - num] { 8 out.append(index) 9 out.append(sum) 10 } 11 dict[num] = index 12 } 13 return out 14 } 15 } 18496 kb1 class Solution { 2 func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 for i in 0...nums.count-1 { 4 if i == nums.count-1 { break; } 5 for j in i+1...nums.count-1 { 6 let sum = nums[i] + nums[j] 7 if sum == target { 8 return [i, j] 9 } 10 } 11 } 12 return [Int]() 13 } 14 } 18524 kb1 class Solution { 2 typealias ArrayIndex = (array: [Int], startIndex: Int) 3 4 func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 5 var arrayTest = [ArrayIndex]() 6 arrayTest.append(ArrayIndex(nums, 0)) 7 8 while arrayTest.count != 0 { 9 let values = arrayTest.remove(at: 0) 10 let splitValues = splitArray(nums: values) 11 if let result = scanTwoArray(nums1: splitValues.nums1, nums2: splitValues.nums2, target: target) { 12 return result 13 } else { 14 arrayTest.append(splitValues.nums1) 15 arrayTest.append(splitValues.nums2) 16 } 17 } 18 return [0,1] 19 } 20 21 func splitArray(nums: ArrayIndex) -> (nums1: ArrayIndex, nums2: ArrayIndex) { 22 let ct = nums.array.count 23 let half = ct / 2 24 let leftSplit = nums.array[0 ..< half] 25 let rightSplit = nums.array[half ..< ct] 26 return ((Array(leftSplit), nums.startIndex), (Array(rightSplit), nums.startIndex + half)) 27 } 28 29 func scanTwoArray(nums1: ArrayIndex, nums2: ArrayIndex, target: Int) -> [Int]? { 30 for i in 0..<nums1.array.count { 31 for j in 0..<nums2.array.count { 32 if nums1.array[i] + nums2.array[j] == target { 33 return [i + nums1.startIndex, j + nums2.startIndex] 34 } 35 } 36 } 37 38 return nil 39 } 40 }
|
请发表评论