美文网首页
2Sum problem

2Sum problem

作者: Leonlong | 来源:发表于2017-01-02 12:11 被阅读0次

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.
** Notice
You may assume that each input would have exactly one solution

用hashmap来做,我们用target减去每个数得到每个数需要的数字,然后把它存在hashmap的key中,value存当前数字的index。
所以每次我们只需用containsKey检测当前数字是否在key中和另一个数配对,如果配对,我们拿出index和当前数字index一起返回。

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum(int[] numbers, int target) {
        // write your code here
        
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for(int i = 0; i < numbers.length; i++) {
            if (map.containsKey(numbers[i])) {
                
                int[] result = {map.get(numbers[i]) + 1, i + 1};
                return result;
            }
            
            map.put(target - numbers[i], i);
        }
        
        int[] result = {};
        return result;
        
        
    }
    
    
    
}

相关文章

  • 2Sum problem

    Given an array of integers, find two numbers such that th...

  • K-sum

    1. 2sum: Given an array of integers, return indices of th...

  • 2Sum算法

    给一个整型数组和一个目标值,判断数组中是否有两个数字之和等于目标值。 这道题是传说中经典的 “2Sum”,我们已经...

  • Ksum 问题

    Ksum,用backtracking来做,转换成1sum or 2sum, 3Sum: https://leetc...

  • HDU 2101 A + B Problem Too

    Problem Description This problem is also a A + B problem,...

  • Your problem is not your problem

    No individuality, no speciality. We are one Self.

  • ACM(eight)

    A + B Problem Too This problem is also a A + B problem,bu...

  • problem

    什么是问题,问题本身不是问题。

  • Problem

    沉默的夜 被五彩的燈光打擾 房間的明亮 有著音樂的加溫 漸漸炙熱起來 她的手優雅地揮舞 配合音樂的節奏 銀光忽而閃...

  • To be or not to be,it' a problem

    一直都知道《哈姆雷特》是本特别有名的书,其中的“生存还是毁灭,这是一个问题”历来被人们称颂,这周在看这本书,看到了...

网友评论

      本文标题:2Sum problem

      本文链接:https://www.haomeiwen.com/subject/hsswvttx.html