diff --git a/Java/leetcode/easy/TwoSum.java b/Java/leetcode/easy/TwoSum.java new file mode 100644 index 0000000..13ab7db --- /dev/null +++ b/Java/leetcode/easy/TwoSum.java @@ -0,0 +1,35 @@ +/** + * Leetcode #1 - Two Sum + * Problem: Given an array of integers, return indices of the two numbers + * such that they add up to a specific target. + * + * Approach: Using HashMap to store number and its index + * Time Complexity: O(n) + * Space Complexity: O(n) + */ + +import java.util.HashMap; +import java.util.Map; + +public class TwoSum { + public int[] twoSum(int[] nums, int target) { + Map 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[] {}; + } + + // Main method for testing + public static void main(String[] args) { + TwoSum solution = new TwoSum(); + int[] nums = {2, 7, 11, 15}; + int target = 9; + int[] result = solution.twoSum(nums, target); + System.out.println("Indices: " + result[0] + ", " + result[1]); + } +} \ No newline at end of file