-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
71 lines (57 loc) · 1.5 KB
/
TwoSum.java
File metadata and controls
71 lines (57 loc) · 1.5 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package leetCode;
public class TwoSum {
/*
* ********************* EXPLANATION ***********************
*
* Given an array of integers nums and an integer target, return indices of the
* two numbers such that they add up to target.
*
* You may assume that each input would have exactly one solution, and you may
* not use the same element twice.
*
* You can return the answer in any order.
*/
public static void main(String[] args) {
int nElementos = (int) (Math.random() * 70);
int nums[] = new int[nElementos];
int numBuscado = 13;
for (int i = 0; i < nums.length; i++) {
int nRandom = generateNRandom();
nums[i] = nRandom;
}
int x[] = twoSum(nums, numBuscado);
System.out.println();
for (int i : nums) {
System.out.print(i + " ");
}
System.out.println();
if (x != null) {
for (int j : x) {
System.out.print(j + " ");
}
}
if (x != null)
System.out.println("\nNUMEROS GUARDADOS EN LAS POSICIONES: " + x[0] + " y " + x[1] + " = " + nums[x[0]]
+ " - " + nums[x[1]]);
}
public static int generateNRandom() {
int nRandom = (int) (Math.random() * 18);
if (nRandom == 0)
return generateNRandom();
return nRandom;
}
public static int[] twoSum(int[] nums, int target) {
int vector[] = new int[2];
for (int i = (nums.length - 1); i >= 0; i--) {
int aux = i;
for (int k = 0; k < i; k++) {
if (nums[aux] + nums[k] == target) {
vector[0] = aux;
vector[1] = k;
return vector;
}
}
}
return null;
}
}