Two Sum – LeetCode 1
Problem
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].
Answer
Original
Code
1 | class Solution { |
思路
从数组nums的第一项开始寻找能加和成为target的另一项,简单粗暴。时间复杂度$O(n^2$),空间复杂度$O(1)$。
耗时$189$ ms,排名$77.08\%$。
Better
思路
利用HashMap中查找操作的理论时间复杂度仅为$O(1)$来省去嵌套遍历的$O(n)$。通过建立一张表来对应所需要的nums[i] - target
这一值,是以空间换时间的手段。 时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$9$ ms,排名$45.75\%$。
Code
1 | class Solution { |