forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-algo.java
41 lines (32 loc) · 1.03 KB
/
add-algo.java
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
38
39
40
41
import java.util.HashMap;
import java.util.Scanner;
import java.util.Map;
class TwoSum {
// Time complexity: O(n^2)
private static int[] findTwoSum_BruteForce(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[] {};
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; i++) {
nums[i] = keyboard.nextInt();
}
int target = keyboard.nextInt();
keyboard.close();
int[] indices = findTwoSum_BruteForce(nums, target);
if (indices.length == 2) {
System.out.println(indices[0] + " " + indices[1]);
} else {
System.out.println("No solution found!");
}
}
}