-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSum.java
50 lines (38 loc) · 984 Bytes
/
TwoSum.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
42
43
44
45
46
47
48
49
50
package com.leetcode.algorithms.easy.twopointers;
import java.util.Arrays;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class TwoSum {
public static void main(String... args) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int[] nums = InputUtil.integerArr(inputs);
int target = scanner.nextInt();
int[] result = twoSum(nums, target);
// Print output
System.out.print(Arrays.toString(result));;
scanner.close();
}
private static int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i = 0; i < nums.length; i++) {
int no1 = nums[i];
for(int j = 0; j < nums.length; j++) {
if(j != i) {
int no2 = nums[j];
int check = no1 + no2;
if (check == target) {
result[0] = i;
result[1] = j;
break;
}
}
}
if(result[0] + result[1] != 0) {
break;
}
}
return result;
}
}