天天看点

Java - LeetCode 1.两数之和(哈希表、暴力解法)(小白入手,全解析)(数组)

哈希表(速度快)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        int [] res = new int [2];
        if(n == 0) return res;
        
        HashMap<Integer,Integer> map = new HashMap<>();

        for (int i = 0; i < n; i++) {
            int value = nums[i];
            int r = target-value; 
            if (map.containsKey(r)) {
                    res[1] = i;
                    res[0] = map.get(r);
                    return res;
            }else{
                map.put(value,i);
            }
        }
        return res;
    }

           

暴力解法(思路简单)

(这个解法,有的人就能编过,但我的力扣一直超出时间限制)

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