【LeetCode】 112 兩數之和

題目:

image-20210201022246604

image-20210201022258832

解題思路:

刷題中的“abandon”,力扣的第一題,但是在牛客148裏作爲第148題,正好相反

HashMap 優雅解法

https://leetcode-cn.com/problems/3sum-closest/solution/zui-jie-jin-de-san-shu-zhi-he-by-leetcode-solution/

代碼:

import java.util.HashMap;
import java.util.Map;

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

    public static void main(String[] args) {
        LC148 lc148 = new LC148();
        int[] arr = new int[]{3,2,4};
        int[] res = lc148.twoSum(arr, 6);
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i]+" ");
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章