サンダーボルト

相手モンスターを全て破壊する。

LeetCode Study : 1. Two Sum

問題

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

https://leetcode.com/problems/two-sum/

自分の解答

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

コード理解

別解は以下の2つ

Two-pass Hash Table

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

Time : O(n) / Space : O(n)

One-pass Hash Table

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);
    }
    throw new IllegalArgumentException("No two sum solution");
}

Time : O(n) / Space : O(n)

自分の解答はBrute Force(力ずく)と呼ばれる。 基本的に、リストの中からelementを見つけるにはindexごとに順に調べていかないといけないO(n)。スペースを犠牲にこの探索スピードを上げるために hash tableが存在する。 hash値で検索できるようにリストをmapに変えてしまえばO(1)で探索が可能になる。

1つ目の別解は一旦全部mapに変換してから検索、2つ目は1つ見るごとにmapにつめていく。1つ目の解では必ず1周しなければいけないので2つ目のOne-pass Hash Tableの方がより高速だと思う。

今後のための考え方

Listの何番目にあるかを調べたい場合は一度HashMapにしてしまえば速い。ただしメモリは食う。