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].
Java
思路:
1.利用HashMap,将输入的数组和index关联,其中数组作为key,index作为value;
- 为什么不能将index作为key,数组作为value?
- 因为输出的是数组的index,而map只有通过key提取value的方法,即map.get(key);
2.通过for循环,既建立map,又遍历循环;
3.输出是两个数的数组,所以要创建一个数组作为return;
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2]; //创建一个数组作为return
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //用<type1,type2>控制类型
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) { //是否含有此值
result[1] = i + 1; //此值较大,返回到后一个上
result[0] = map.get(target - numbers[i]); //此值较小,返回到前一个上
return result; //结果返回
}
map.put(numbers[i], i + 1); //map添加
}
return result; //结果返回
}
Python
following is python code:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
self.list = nums
self.target = target
for i in range(0, len(self.list)):
for j in range(0, len(self.list)):
if i == j:
pass
else:
if self.target == self.list[i] +self.list[j]:
newlist = [i, j]
newlist = sorted(newlist)
return newlist
following is python code developed:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
self.list = nums
self.target = target
for i in range(0, len(self.list)):
for j in range(i+1, len(self.list)):
if self.target == self.list[i] + self.list[j]:
newlist = [i, j]
return newlist