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, 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].
result:
//typescript
var twoSum=function(nums:Array<number>,target:number):Array<number>{
let len=nums.length;
let obj={};
for(let i=0;i<len;i++){
if(obj[target-nums[i]]!==undefined){
return [obj[target-nums[i]],i];
}
obj[nums[i]]=i;//翻转 key value
}
}
//python3
def twoSum(nums,target):
dict={};
for i in range(len(nums)):
if target-nums[i] in dict:
return dict[target-nums[i]],i;
dict[nums[i]]=i;
result=twoSum([1,2,3,-1],0);
print(result);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。