Difficulty:
simple
Description:
Given an array of integers nums and a target value target, find the two integers in the array and the target values and return their array subscripts. You can assume that there is only one answer for each type of input. However, you cannot reuse the same elements in this array.
Example:
Given nums = [2, 7, 11, 15], target = 9Copy the code
Source: LeetCode link: leetcode-cn.com/problems/tw… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Language:
swift
Resolution:
Number1 + number2 = target, number1 can be iterated through the array, but number2 can’t be iterated through the array, because it would be O(n^2), and the code would look ugly. So number2 = target-number1, we can save each number as we go through the number array, and then get each number, and use the difference of target-number to determine whether there is a target number. We use dictionaries for storage, because hashMap is faster. And to avoid reusing an element of the array, we don’t do anything when it has a value.
The code is as follows:
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var hashMap = [Int: Int]()
for index in0... nums.count - 1 {let minusValue = target - nums[index]
if hashMap[minusValue] ! = nil && index ! =hashMap[minusValue] {
return [hashMap[minusValue]! , index] }else {
hashMap[nums[index]] = index
}
}
return[]}}Copy the code
conclusion
I think hashMaps work well in the right context.