LeetCode 1 Two sum Java

来源:互联网 发布:淘宝网店装修工具 编辑:程序博客网 时间:2024/06/16 21:49

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

空间换时间:

程序转自:https://leetcode.com/discuss/41366/my-short-java-solution-o-n-hashmap

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