Two Sum
来源:互联网 发布:新页软件破解 编辑:程序博客网 时间:2024/05/22 09:02
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 thesame element twice.
给定一组整数,两个数字的返回索引,这样它们就会加到一个特定的目标上。
您可能假设每个输入都有一个解决方案,并且您可能不使用相同的元素两次。
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
JAVA
public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i); } return result;}
PYTHON
def twoSum(self, nums, target): d={} for i,num in enumerate(nums): if target-num in d: return d[target-num]+1, i+1 d[num]=i
阅读全文