文章--LeetCode算法--TwoSum
TwoSum
问题描述
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].
解决思路
思路:查找时,建立索引(Hash查找)或进行排序(二分查找)。本题缓存可在找的过程中建立索引,故一个循环可以求出解(总是使用未
使用元素查找使用元素,可以保证每一对都被检索到)。Indexing/ordering is the first step to search questions.
实现代码
package com.leetcode.play;
import java.util.HashMap;
import java.util.Map;
/**
* 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].
* @since 1.8
*/
public class TwoSum {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9 ;
int[] ints = twoSum(nums,target);
for (int i:ints) {
System.out.println(i);
}
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
int num = target - nums[i];
if (m.containsKey(num))
return new int[] {m.get(num), i};
m.put(nums[i], i);
}
throw new RuntimeException("no answer!");
}
}