Leetcode-[難度中] 兩數之和

題目描述

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。

你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個數組中同樣的元素。

例:

給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

題目解析

思路:使用查找表來解決該問題。

設置一個 hashmap 容器 record 用來記錄元素的值與索引,然後遍歷數組 nums。

  • 每次遍歷時使用臨時變量 diff 用來保存目標值與當前值的差值

  • 在此次遍歷中查找 record ,查看是否有與 diff 一致的值,如果查找成功則返回查找值的索引值與當前變量的值 i

  • 如果未找到,則在 record 保存該元素與索引值 i

Coding

public class TwoSum {

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

    public static void main(String[] args) {
        int[] nums = {2, 5, 7, 11};
        int[] index = twoSum(nums, 9);
        if (index.length == 2) {
            System.out.println(index[0]);
            System.out.println(index[1]);
        }
    }

}

感謝你的關注,請關注作者公衆號:

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