leetcode:Two Sum 【Java】

来源:互联网 发布:linux查看当前路径 编辑:程序博客网 时间:2024/06/05 04:55

一、问题描述

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.

二、问题分析

注意nums数组中可能存在重复元素(附录中程序无法解决该问题),例如nums = [0,2,3,0],target = 0,正确结果应该是[0,3]而不是[3,3].

三、算法代码

public class Solution {    public int[] twoSum(int[] nums, int target) {        HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();int gap = -1;Integer index;int [] result = new int[]{-1,-1};for(int i = 0; i <= nums.length - 1; i++){gap = target - nums[i];index = map.get(gap);if(index == null){map.put(nums[i], i);}else{result[0] = index;result[1] = i;break;}}return result;    }}
四、附录

public static int[] twoSum(int[] nums, int target) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();for(int i = 0; i <= nums.length - 1; i++){map.put(nums[i], i);}int [] result = new int[]{-1, -1};int first = -1;int second = -1;for(int j = 0; j <= target / 2; j++){first = j;second = target - j;if(map.containsKey(first) && map.containsKey(second)){result[0] = map.get(first);result[1] = map.get(second);break;}}        return result;    }



0 0
原创粉丝点击