文章背景图

重温 Leetcode hot 100

2025-12-01
7
-
- 分钟
|

哈希

1. 两数之和

1. 两数之和 - 力扣(LeetCode)

暴力法:

JAVA版本:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0;i < nums.length - 1;i++){
            for(int j = i + 1;j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }
}

哈希法:

JAVA版本:

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

golang版本

func twoSum(nums []int, target int) []int {
    nums_map := make(map[int]int)
    nums_map[target - nums[0]] = 0
    for i := 1;i<len(nums);i++{
        idx,ok := nums_map[nums[i]]
        if ok{
            return []int{idx,i}
        }
        nums_map[target - nums[i]] = i
    }
    return nil
}

原创

重温 Leetcode hot 100

本文链接: 重温 Leetcode hot 100

本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

上一篇 python 学习
下一篇 没有了
评论交流

文章目录