Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Java/leetcode/easy/TwoSum.java
Original file line number Diff line number Diff line change
@@ -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<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);
}
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]);
}
}