LeetCode Two Sum Java解決方案

Two Sum Java解決方案

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, and you may not use the same element twice.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

問題解讀

這個問題使用Java是相對好解決的。

首先對問題進行解讀,給出一個數組。如果數組中特定的兩個數相加得到的數恰好爲target,那麼就以數組的形式返回這兩個數的索引值。

結合例子,題目還提出每個樣本都會有解答並且不會重複使用同一個元素。

本人使用了HashMap,其中Key代表數組中的每一個值,而Value代表對應的索引。

遍歷數組並進行判斷,如果map中的key恰好有數組中遍歷到的值,就會停止遍歷。

如果遍歷到的nums[i]並不存在於map中,則對於數組這一項的值都用target值減去,並把(target-nums[i],i)存儲到map中。

這裏利用了這樣思想,把(target-nums[i])作爲key存儲到map中,當遍歷到的nums[j]與target-nums[j]恰好相等時,則說明存在兩個數相加的值爲target。

所以在匹配到停止遍歷時,返回nums[i]在map中的索引值和遍歷到的索引值i組合成的數組,即可。(這裏可能需要自己思考舉例)

Java代碼

public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> numMap = new HashMap<>();
        int len = nums.length;
    for(int i=0;i<len;i++){
            if(numMap.containsKey(nums[i])){
                int index = numMap.get(nums[i]);
                return new int[]{index,i};
            }else{
                numMap.put(target-nums[i],i);
            }
        }
        return new int[2];
    }

運行複雜度

Runtime 2 ms
Memory 37.3 MB
Language java

發佈了24 篇原創文章 · 獲贊 15 · 訪問量 9827
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章