Problem
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.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
- 2 <= nums.length <= 103
- -109 <= nums[i] <= 109
- -109 <= target <= 109
- Only one valid answer exists.
Solution
function twoSum(nums: number[], target: number): number[] {
let map = new Map();
nums.forEach(num=>{map.set(num,nums.indexOf(num));})
for(let i=0;i<nums.length;i++){
var n = target-nums[i];
if(map.has(n) && map.get(n)!=i){
return [i,map.get(n)];
}
}
};
心得
第一题就难住我了,然后看了评论发现不止我一个人觉得难,但是万事总是开头难的,相信以后习惯就好。
个人感觉leetcode的题目其实和解数学题有些相似,都得用点特别的、讨巧的方法才行。
这一题一开始自己做超时了,然后看别人利用差值的思路写出来的,这里它只给了两数之和与数组,隐藏的条件是由和与一个数可以得到另一个数,同时这另一个数也必然是存在于这个数组中的,这样的解答就比较巧妙了。
来源:
力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。