您的位置:首页 > 其它

LeetCode Two Sum

2015-05-25 21:18 309 查看
Description:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

Solution:

We use the HashMap here to solve this interesting problem.

First, we go through all the integers in the array, then we put the <nums[i], i+1> as <key, value> into the HashMap.

Then we go through the array again. For each integer, we can get the pair <nums[i], i>, then we want to find out if there exists pair <nums[j], j> which meets the demand that nums[i] + nums[j] = number. So we use the if statement HashMap.containsKey(number
- nums[i]). If so, we can get the answer i+1 and j+1.

Notice: for the input {3,3}, 6, we should output {1, 2}. And how can we reach this goal?

HashMap has an interesting feature that everytime it put the <key, value> with the same key, the value will be the latest one. So below is how the HashMap goes:

<3, 1>

<3, 2>

So when we go through all the numbers in the second step, i=0, we can get HashMap.containsKey(3) = 2 != 1. So problem solved.

import java.util.HashMap;

public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int l = nums.length;
for (int i = 0; i < l; i++)
map.put(nums[i], i + 1);

int ans[] = new int[2];
for (int i = 0; i < l; i++) {
if (map.containsKey(target - nums[i])
&& map.get(target - nums[i]) != i + 1) {
ans[0] = i + 1;
ans[1] = map.get(target - nums[i]);
break;
}
}

return ans;
}

public static void main(String[] args) {
int arr[] = { 3, 3, 2 };
Solution s = new Solution();
s.twoSum(arr, 6);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: