LeetCode Hot100(持续更新中)

一、哈希

(一)两数之和

LeetCode Hot100(持续更新中)_第1张图片

思路一:传统方法-双层循环遍历
时间复杂度:O(n^2)

空间复杂度:O(1)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 两层循环求解 时间复杂度O(N^2) 空间复杂度O(1)
        int[] goal = new int[2];

        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if ( (nums[i] + nums[j]) == target ) {
                    goal[0] = i;
                    goal[1] = j;
                    return goal;
                }
            }
        }

        throw new IllegalArgumentException("no such two nums.");
    }
}

思路二:HashMap方法-一次遍历
时间复杂度:O(n)

空间复杂度:O(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // HashMap求解 时间复杂度O(N) 空间复杂度O(N)
        Map numsMap = new HashMap();

        numsMap.put(nums[0], 0);

        for (int i = 1; i < nums.length; i++) {
            // 计算当前值距离目标值的补数
            int complement = target - nums[i];
            // 查看当前补数是否存在numsMap中
            if (numsMap.containsKey(complement)) {
                return new int[] { numsMap.get(complement), i};
            }
            // 不存在,将当前值加入numsMap中
            numsMap.put(nums[i], i);
        }

        throw new IllegalArgumentException("未找到符合要求的两个下标");
        
    }
}

你可能感兴趣的:(LeetCode,Hot100,leetcode,算法)