From 5400059df7c245bbb0ff8e7828dfaf5bcbf964bc Mon Sep 17 00:00:00 2001 From: Abhaytomar2004 Date: Sun, 5 Oct 2025 17:32:05 +0530 Subject: [PATCH] feat: add Java competitive programming solutions --- Java/leetcode/easy/TwoSum.java | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Java/leetcode/easy/TwoSum.java 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