LeetCode 151 Two Sum

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

分析:

這個題跟典型的k Sum有所不同,不同點在於,不要求結果是有序的,而是要返回下標,所以不能按順序遍歷。

用HashMap將 target - num[i] 和 i 的鍵值對存起來,那麼當遍歷到值爲 target-num[i] 的 j 時,可以從HashMap中取出 i。

因爲要求返回下標是1開始的,那麼就是 i+1,j+1。

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
       int[] res = new int[2];
       HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
       for(int i=0; i<numbers.length; i++){
           if(map.containsKey(numbers[i])){
               int index = map.get(numbers[i]);
               res[0] = index+1;
               res[1] = i+1;
               break;
           }else{
               map.put(target-numbers[i], i);
           }
       }
       return res;
    }
}

另一種解法,原理是一樣的,不同點在與放進HashMap得時numbers[i] 和 i 對,跟直觀一點。

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0; i<numbers.length; i++){
            if(map.containsKey(target-numbers[i])){
                res[0] = map.get(target-numbers[i])+1;
                res[1] = i+1;
            }else{
                map.put(numbers[i], i);
            }
        }
        return res;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章