diff --git a/hashmap/1.md b/hashmap/1.md new file mode 100644 index 0000000..9081546 --- /dev/null +++ b/hashmap/1.md @@ -0,0 +1,77 @@ +# 1st +- 問題: [1. Two Sum](https://leetcode.com/problems/two-sum/) +- コメント集: [1. Two Sum](https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/mobilebasic#h.7b7phcxky0ug) + - [身体性を持った考え方があるよね](https://discord.com/channels/1084280443945353267/1237649827240742942/1249892025948573706) + - [1000枚のカードが配られて、2枚のカードの和がある数になる時、2枚のカードをどう探しますか?](https://discord.com/channels/1084280443945353267/1229085360403775569/1229955174446137344) + - [類似コメント](https://discord.com/channels/1084280443945353267/1218823752243089408/1239214204742013009) + - なるほど、これはその通りだし、解法が自然に思いつくと感じた + - こういう言い換えを頭の中で行なって解法を組み立て、相手に説明すればいいな + - [Exceptionの話1](https://discord.com/channels/1084280443945353267/1263078966491877377/1296874739377115243) + - [Exceptionの話2](https://discord.com/channels/1084280443945353267/1346189624414048360/1346775042322862152) + - [データ構造の名称を変数名として使うなの話](http://discord.com/channels/1084280443945353267/1337068598337736838/1338007445892763732) + - これ自分も最初に書く時にやりがちなので反省 + - 「例えば、部屋という抽象的な単語は文脈に応じて具体的な名前(会議室、食堂)で呼ぶでしょ?」という話 +- 条件 + - `2 <= nums.length <= 10^4` + - `-10^9 <= nums[i] <= 10^9` + - `-10^9 <= target <= 10^9` +- 方針 + - 数字2つのペアの和が必ず target を満たすので、一回のループを回しながら target - nums[i] を hashmap に記録していく + - nums[i]以降を走査する時、すでに map に nums[i以降]がkeyとしてあれば、mapに記録しているインデックスと今走査しているインデックスの組み合わせが答えとなる + - 時間計算量: O(N) + - 空間計算量: O(N) +- 時間 + - 10分 + +```java +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + if (map.containsKey(nums[i])) { + return new int[]{map.get(nums[i]), i}; + } + int temp = target - nums[i]; + map.put(temp, i); + } + return null; + } +} +``` + +## 2nd +- 変数名を綺麗にする +- null を返していたが、Exception が適切だと判断した +```java +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap complementToIndex = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + if (complementToIndex.containsKey(nums[i])) { + return new int[]{complementToIndex.get(nums[i]), i}; + } + int complement = target - nums[i]; + complementToIndex.put(complement, i); + } + throw new IllegalArgumentException("numsに含まれる要素のペアで、和がtargetを満たすものは存在しない"); + } +} +``` + +## 3rd +- 3回かく +```java +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap complementToIndex = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + if (complementToIndex.containsKey(nums[i])) { + return new int[]{complementToIndex.get(nums[i]), i}; + } + int complement = target - nums[i]; + complementToIndex.put(complement, i); + } + throw new IllegalArgumentException("numsに含まれる要素のペアで、和がtargetを満たすものは存在しない"); + } +} +``` \ No newline at end of file