preface
Our community will start this issue with yi Gu, Netflix growth hacker, author of The iOS Interview Guide and ACE Professional fitness coach. Swift algorithm solution sorted into text version to facilitate everyone to learn and read.
Short step, no thousands of miles; No small streams, no rivers and seas, Swift community with you forward.
1. Describe
Given an integer array nums and an integer target, take the sum of any two values in the array and return the index of the two values in the array.
Assumptions:
- There’s only one valid answer
- You cannot take the same value twice
- Answers can be returned in any order
Example 2.
Example 1
Input: nums = [2,7,11,15], target = 9 output: [0,1]Copy the code
Example 2
Input: nums = [3,2,4], target = 6Copy the code
Example 3
Input: nums = [3,3], target = 6Copy the code
3. The answer
class TwoSum {
func twoSum(_ nums: [Int]._ target: Int)- > [Int] {
var dict = [Int: Int] ()for (i, num) in nums.enumerated() {
if let lastIndex = dict[target - num] {
return [lastIndex, i]
}
dict[num] = i
}
fatalError("No valid outputs")}}Copy the code
- Main idea: Iterate over a number set and store the target in a dictionary – nums[I]
- Time complexity: O(n)
- Space complexity: O(n)
The github repository address for this algorithm is: github.com/soapyigu/Le…
Click to go to LeetCode practice