01.leetcode_twoSum

Posted xulimessage

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了01.leetcode_twoSum相关的知识,希望对你有一定的参考价值。

问题
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].

The return format had been changed to zero-based indices. Please read the above updated description carefully.


代码

import java.util.HashMap;

public class twoSum 
    public int[] twoSum(int[] numbers, int target) 
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];

        for (int i = 0; i < numbers.length; i++) 

            if (map.containsKey(target - numbers[i])) 
                res[1] = map.get(target-numbers[i]);
                res[0] = i;
                break;
            
            map.put(numbers[i], i);
        


        return res;

    

    public static void main(String[] args) 
        int [] num = 1,2,3,4,5;
        twoSum twoSum = new twoSum();
        int[] ints = twoSum.twoSum(num, 6);
        for (int i = 0; i < ints.length; i++) 
            System.out.println(ints[i]);

        
    

以上是关于01.leetcode_twoSum的主要内容,如果未能解决你的问题,请参考以下文章