leetcode-1-two sum

题目

对于给定的数组,给定一个target数值,如果数组中的某两个元素的和为target,返回两个元素在数组中的下标

描述

假设输入有唯一的输出!!
举例说明
给定 nums = [2, 7, 11, 15], target = 9,由于nums[0] + nums[1] = 2 + 7 = 9,
所以输出return [0,1]

Java代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class  {
public int[] twoSum(int[] nums, int target) {
int [] result = new int[2];
int len = nums.length;
HashMap <Integer,Integer> h = new HashMap <Integer,Integer>();
for(int i = 0; i<len; i++){
if(h.containsKey(target-nums[i])){
result[0] = Math.min(h.get(target-nums[i]), i);
result[1] = Math.max(h.get(target-nums[i]), i);
break;
}
h.put(nums[i],i);
}
return result;
}
}

Python代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class (object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

dic = {};
result = [];
for i in range(len(nums)):
if(dic.has_key(target - nums[i])):
result.append( min(dic[target-nums[i]],i) )
result.append( max(dic[target-nums[i]],i) )
else:
dic[nums[i]] =i
return result