LeetCode Two Sum I and II

December 25, 2020

Two Sum I

題目內容是說從給予的陣列中找出兩個索引值相加等於給定目標值。這邊使用 HashMap 的概念實現題目要求。

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

Two Sum II

題目相較於第一版本對陣列進行排序。思路是使用兩個指針方式進行遍歷。

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int start = 0;
        int end = numbers.length - 1;
        while ((numbers[start] + numbers[end]) != target){
            int sum = numbers[start] + numbers[end];
            if ( sum > target){
                end--;
            } else {
                start++;
            }
        }
        
        return new int[]{start + 1, end + 1};
    }
}