1. 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.
给一个整数数组,给一个数字,返回数组中两个数字的序号,这两个数字加起来等于给定数字。
假设每个输入只有一个确定的解。
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int len = nums.length;
int[] defaultResult ={0,0};
for(int i = 0; i < len; i++){
if(map.get(target-nums[i]) != null){
int[] result = {map.get(target-nums[i]), i};
return result;
}
map.put(nums[i], i);
}
return defaultResult;
}
}
new一个HashMap,得到数组长度,初始化结果。
给定数字减数组中数字,其结果没在map中,就加入map。有就返回两个数字的序号。
HashMap中是key-value,对此题目,数字作为key,序号为value