2Sum problem

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減去每個數(shù)得到每個數(shù)需要的數(shù)字,然后把它存在hashmap的key中,value存當前數(shù)字的index。
所以每次我們只需用containsKey檢測當前數(shù)字是否在key中和另一個數(shù)配對,如果配對,我們拿出index和當前數(shù)字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;
        
        
    }
    
    
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容