Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
First Try:
1 | /** |
Runtime: 112 ms, faster than 45.07% of JavaScript online submissions for Two Sum.
Memory Usage: 39.5 MB, less than 73.12% of JavaScript online submissions for Two Sum.
Feedback and improve
do not use var in a function(), use let.
Time complexity:o(n2); space complexity:o(1)
we can use map to reduce time complexity, by sacrificing space.
map{[kay:value],[key:value],[key:value],…}
map[key]=value
1 | /** |
Runtime: 64 ms, faster than 99.36% of JavaScript online submissions for Two Sum.
Memory Usage: 40 MB, less than 55.97% of JavaScript online submissions for Two Sum.
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !