-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo Sum.java
More file actions
61 lines (50 loc) · 1.46 KB
/
Two Sum.java
File metadata and controls
61 lines (50 loc) · 1.46 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
class Solution {
public int[] twoSum(int[] numbers, int target) {
int len = numbers.length;
int[] result = new int[2] ;
int number1 = 0;
int sum = 0;
for (int i = 0; i < len; i++) {
number1 = numbers[i];
for(int j = i+1; j < len; j++)
{
sum = number1+numbers[j];
if(sum == target)
{
result[0]=i;
result[1]=j;
}
}
}
return result;
}
}
//Brute force method
class Solution{
public int[] twoSum(int[] num,int target){
for(int i=0;i<num.length;i++){
for(int j=i+1;j<num.length;j++){
if(num[j]==target-num[i]){
return new int[] {i,j};
}
}
}
return null;
}
}
//Efficient solution using hashmap
class Solution{
public int[] twoSum(int[] num,int target){
int[] result=new int[2];
HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<num.length;i++){
if(map.containsKey(target-num[i])){
return new int[] {map.get(target-num[i]),i};
}
else{
map.put(num[i],i);
}
}
throw new IllegalArgumentException("No two sum solution");
}
}