LeetCode Link: https://leetcode-cn.com/problems/two-sum
Description:
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].
Tints:
1.因为要求返回的是两个数的下标,创建一个空的字典,key为nums中的数,value为该数的下标
2.遍历数组,遍历到的数为num,用dict[target-num]判断在字典中是否存在另一个数使得两个数相加为目标值,如果存在,直接返回两个下标,如果不存在,往字典中存入该数以及它的下标
Solution:
import Foundation
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dic = [Int: Int]()
for (index1, num) in nums.enumerated() {
if let index2 = dic[target - num] {
return [index2, index1]
} else {
dic[num] = index1
}
}
fatalError("No valid output!")
}
Runtime: 32 ms - beats 100.00 % of swift submissions.
Memory Usage: 19.1 MB - beats 53.98 % of swift submissions.
Analyze:
1.用字典查找所用时间为O(1)
2.fatalError:Apple 对其的描述:Unconditionally prints a given message and stops execution.无条件的打印出给定的信息同时终止程序