From 4ddd37e4c28eedf4fecd42e8d4e201cfd4a5abcb Mon Sep 17 00:00:00 2001 From: KAMS Date: Sat, 15 Nov 2025 22:17:34 +0900 Subject: [PATCH] two sum solution --- two-sum/Sol35229.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 two-sum/Sol35229.java diff --git a/two-sum/Sol35229.java b/two-sum/Sol35229.java new file mode 100644 index 000000000..059db5bdd --- /dev/null +++ b/two-sum/Sol35229.java @@ -0,0 +1,31 @@ +import java.util.HashMap; +import java.util.Map; + +public class Sol35229 { + + public int[] bruteForce(int[] nums, int target) { + for (int i = 0; i < nums.length; i++) { + for (int j = i+1; j < nums.length; j++) { + if (nums[i]+nums[j] == target) { + return new int[]{i, j}; + } + } + } + return new int[] {}; + } + + public int[] hashTable(int[] nums, int target) { + Map hashMap = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + hashMap.put(nums[i], i); + } + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + if (hashMap.containsKey(complement) && hashMap.get(complement) != i) { + return new int[]{i, hashMap.get(complement)}; + } + } + return new int[] {}; + } +} +