LeetCode题解:Two Sum

来源:互联网 发布:淘宝代销分账怎么设置 编辑:程序博客网 时间:2024/06/05 20:12

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

题意:给定一个数组,找出其中两个元素的和为给定整数

解题思路:用HashMap建立数组元素与目标整数的差的映射,存在就是有

代码:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] result = new int[2];        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int i = 0; i < nums.length; i++){            if(map.containsKey(target - nums[i])){                result[0] = map.get(target - nums[i]);                result[1] = i + 1;                return result;            }else{                map.put(nums[i], i + 1);            }        }        return result;    }}
0 0
原创粉丝点击