Two Sum
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.
Example:
1 | Given nums = [2, 7, 11, 15], target = 9, |
题目大意
这题大概意思是给一个数字数组和一个目标值,如果数组里面有两个元素的和为这个目标值,返回这两个值的索引。
你可以假设每个输入都有解决方案,其实就是让你少写一些无用的判断。
值得注意的是two numbers, 所以可以忽略target为某一个值两倍的情况。
Solution1: 暴力破解法
1 | var twoSum = function (nums, target) { |
这个方法想必大家都能想到,简单粗暴,复杂度是 O(n^2)
Solution2 index判断法
1 | var twoSum = function (nums, target) { |
这个方法是将数组中的元素当做 key 存入一个 Map (使用原生js对象也可以),然后通过检验是否存在一个 key = target - nums[i] 判断,时间复杂度是 O(n)
刚刚入门算法,大神莫喷,欢迎指正。