兩數(shù)之和

題目

//給定一個整數(shù)數(shù)組 nums 和一個整數(shù)目標值 target,請你在該數(shù)組中找出 和為目標值 target 的那 兩個 整數(shù),并返回它們的數(shù)組下標。 
//
// 你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,數(shù)組中同一個元素在答案里不能重復(fù)出現(xiàn)。 
//
// 你可以按任意順序返回答案。 
//
// 
//
// 示例 1: 
//
// 
//輸入:nums = [2,7,11,15], target = 9
//輸出:[0,1]
//解釋:因為 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
// 
//
// 示例 2: 
//
// 
//輸入:nums = [3,2,4], target = 6
//輸出:[1,2]
// 
//
// 示例 3: 
//
// 
//輸入:nums = [3,3], target = 6
//輸出:[0,1]
// 
//
// 
//
// 提示: 
//
// 
// 2 <= nums.length <= 104 
// -109 <= nums[i] <= 109 
// -109 <= target <= 109 
// 只會存在一個有效答案 
// 
//
// 
//
// 進階:你可以想出一個時間復(fù)雜度小于 O(n2) 的算法嗎? 
// Related Topics 數(shù)組 哈希表 
// ?? 17130 ?? 0


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] twoSum(int[] nums, int target) {

    }
}
//leetcode submit region end(Prohibit modification and deletion)

思路

  1. 用HashMap把值、下標存儲起來,方便查找
  2. 判斷HashMap中是否有 (target-當(dāng)前值)

實現(xiàn)

public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i=0;i<nums.length;i++){
            map.put(nums[i],i);
        }
        int[] res = new int[2];
        for (int i=0;i<nums.length;i++){
            int temp = target - nums[i];
          //判斷是否存在,并且不能是同一個數(shù)據(jù)
            if (map.containsKey(temp) && map.get(temp)!=i){
                res[0] = i;
                res[1] = map.get(temp);
            }
        }
        return res;
    }

結(jié)果

    info
        解答成功:
        執(zhí)行耗時:5 ms,擊敗了48.61% 的Java用戶
        內(nèi)存消耗:42.4 MB,擊敗了28.75% 的Java用戶

思路

遍歷了兩次,這里能不能優(yōu)化一下呢?

優(yōu)化

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

結(jié)果

    info
        解答成功:
        執(zhí)行耗時:1 ms,擊敗了98.28% 的Java用戶
        內(nèi)存消耗:42.6 MB,擊敗了18.89% 的Java用戶
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • 題目 分析 這道題目給我們一個數(shù)組,數(shù)組里面全是整數(shù),然后再給我們一個數(shù)字 target,需要我們求出在這個數(shù)組中...
    zzpwestlife閱讀 394評論 1 2
  • 問題描述: 給定一個整數(shù)數(shù)組 nums 和一個目標值 target,請你在該數(shù)組中找出和為目標值的那 兩個 整數(shù),...
    小天使淘淘閱讀 188評論 0 0
  • 不積硅步無以至千里 leetcode題庫第一題——兩數(shù)之和給定一個整數(shù)數(shù)組和一個整數(shù)目標值,返回兩個數(shù)的下標,這兩...
    All_about_love閱讀 220評論 0 0
  • 問題描述: 給定一個整數(shù)數(shù)組和一個目標值,找出數(shù)組中和為目標值的兩個數(shù)。 你可以假設(shè)每個輸入只對應(yīng)一種答案,且同樣...
    sqing啊閱讀 550評論 0 0
  • Two Sum 兩數(shù)之和 Given an array of integers, return indices o...
    Avery_up閱讀 674評論 0 0

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