【LeetCode】001.Two Sum

来源:互联网 发布:飞天侠淘宝客演示 编辑:程序博客网 时间:2024/06/08 07:40

题目:

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

解答:

遍历数组,直到找到满足要求的值。为了提高查询速度,用LinkedHashMap,这样只需遍历1次,而且不用回溯。细节之处是注意重复值的情况。

代码:

import java.util.*;public class Solution {    public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();// store duplicate valuesMap<Integer, Integer> map2 = new LinkedHashMap<Integer, Integer>();for (int i = 0; i < nums.length; i++) {if (map.containsKey(nums[i]))map2.put(nums[i], i + 1);elsemap.put(nums[i], i + 1);}int index1 = 0, index2 = 0;for (int i : map.keySet()) {index1 = map.get(i);if (i == target - i) {if (map2.containsKey(target - i)) {index2 = map2.get(target - i);break;}} else if (map.containsKey(target - i)) {index2 = map.get(target - i);break;}}return new int[] { index1, index2 };}}


0 0
原创粉丝点击