LeetCode57. 和为s的两个数字

80 阅读1分钟

PK创意闹新春,我正在参加「春节创意投稿大赛」,详情请看:春节创意投稿大赛

image.png

思路1: hash

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.get(target - num) != null) {
                return new int[]{num, target - num};
            }
            map.put(num, num);
        }
        return null;
    }
}

使用hash存储, 跟两数之和一个解法.

思路2: 双指针

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

双指针对撞, 大于左移右指针, 小于右移左指针, 等于则返回.