1. Two Sum(leetcode)

Description

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

idea

本題和lintcode 題目有點(diǎn)區(qū)別,本題允許兩個(gè)重復(fù)數(shù)出現(xiàn),比如數(shù)組 [3, 3] target = 6,如果按照 lintcode 代碼會(huì)出現(xiàn),results = [1, 1] 而實(shí)際上我們要的是 [0, 1],所以需要用 if (hash.containsKey(complement) && hash.get(complement) != i) 做一個(gè)特判,保證在給 results[0] 和 results[1] 賦值時(shí)不出現(xiàn)重復(fù),但還有一點(diǎn)需要強(qiáng)調(diào)的是之前在賦值時(shí)寫的代碼是results[1] = hash.get(nums[i]),這么寫在出現(xiàn)上述 [3, 3] 這種帶有元素的重復(fù)數(shù)組會(huì)有問題,盡管 if 條件句做了特判,但賦值時(shí)可能 hash.get(complement)hash.get(nums[i]) 得到的是同一個(gè)值,所以要直接寫 results[1] = i

Code

  1. 遍歷兩次 hashTable
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] results = new int[2];
        if (nums == null || nums.length == 0) {
           return results;
        }
        
        Map<Integer, Integer> hash = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            hash.put(nums[i], i);
        }
        
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (hash.containsKey(complement) && hash.get(complement) != i) {
                results[0] = hash.get(complement);
                results[1] = i;
            }
        }
        return results;
    }
}
  1. 遍歷一次 hashTable
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] results = new int[2];
        if (nums == null || nums.length == 0) {
           return results;
        }
        
        Map<Integer, Integer> hash = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (hash.containsKey(complement) && hash.get(complement) != i) {
                results[0] = hash.get(complement);
                results[1] = i;
            }
            hash.put(nums[i], i);
        }
        return results;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容