LeetCode-Swift | Solutions to LeetCode by Swift | Learning library
kandi X-RAY | LeetCode-Swift Summary
kandi X-RAY | LeetCode-Swift Summary
Solutions to LeetCode by Swift
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of LeetCode-Swift
LeetCode-Swift Key Features
LeetCode-Swift Examples and Code Snippets
Community Discussions
Trending Discussions on LeetCode-Swift
QUESTION
I just started learning coding with swift, and was trying TwoSum.
"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]."
I found some solutions from GitHub that I cannot understand.
code is from https://github.com/soapyigu/LeetCode-Swift/blob/master/Array/TwoSum.swift
...ANSWER
Answered 2018-Dec-17 at 00:35The dict
initialised in the method stores the numbers in the input as keys, and their indices as values. The program uses this to remember which number is where. The dict
can tell you things like "the number 2 is at index 0".
For each number num
at index i
in the input array, we subtract num
from the target
to find the other number that we need, in order for them to add up to target
.
Now we have the other number we need, we check to see if we have seen such a number before, by searching dict
. This is what the if let lastIndex = dict[target - num]
part is doing. If the dict
knows what index the other number is at, we return that index, and i
.
If we haven't seen that number before, we record i
into the dictionary under the key num
, hoping that in later iterations, we can find a number that when added to num
, makes 9.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install LeetCode-Swift
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page