天天看點

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;
    }
}