forked from 0xsec-debug/Assignment-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSumInput.java
More file actions
35 lines (32 loc) · 1.1 KB
/
TwoSumInput.java
File metadata and controls
35 lines (32 loc) · 1.1 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
import java.util.*;
public class TwoSumInput {
public static int[] twoSum(int[] nums, int target) {
HashMap<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[0];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int[] nums = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
System.out.print("Enter target: ");
int target = sc.nextInt();
int[] result = twoSum(nums, target);
if (result.length == 2) {
System.out.println("Indices: [" + result[0] + ", " + result[1] + "]");
} else {
System.out.println("No valid pair found.");
}
}
}