-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.two-sum.java
More file actions
39 lines (32 loc) · 1.07 KB
/
1.two-sum.java
File metadata and controls
39 lines (32 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.HashMap;
/*
* @lc app=leetcode id=1 lang=java
*
* [1] Two Sum
*/
// @lc code=start
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap <Integer, Integer> valueMap = new HashMap<>();
for(int x=0; x < nums.length; x++){
int difference = target - nums[x];
if(valueMap.containsKey(difference)) return new int[]{valueMap.get(difference),x};
valueMap.put(nums[x], x);
}
throw new IllegalArgumentException("No two sum solution");
}
public static void main(String[] args){
Solution sol = new Solution();
// Test case 1
int[] nums1 = {2, 7, 11, 15};
int target1 = 9;
int[] result1 = sol.twoSum(nums1, target1);
System.out.println("Test 1: [" + result1[0] + ", " + result1[1] + "]");
// Test case 2
int[] nums2 = {3, 2, 4};
int target2 = 6;
int[] result2 = sol.twoSum(nums2, target2);
System.out.println("Test 2: [" + result2[0] + ", " + result2[1] + "]");
}
}
// @lc code=end