-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava
More file actions
52 lines (48 loc) · 1.01 KB
/
Java
File metadata and controls
52 lines (48 loc) · 1.01 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
# Java
1. Brute-Force Approach :
class Solution
{
public int[] twoSum(int[] nums, int target)
{
int n=nums.length,i,j;
int[] arr=new int[2];
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(nums[i]+nums[j]==target)
{
arr[0]=i;
arr[1]=j;
break;
}
}
}
return arr;
}
}
2. Optimal Approach : (Hashmap)
class Solution
{
public int[] twoSum(int[] nums, int target)
{
int[] arr=new int[2];
HashMap<Integer,Integer> map=new HashMap<>();
int i,n=nums.length,num,diff;
for(i=0;i<n;i++)
{
num=nums[i];
diff=target-num;
if(map.containsKey(diff))
{
arr[0]=map.get(diff);
arr[1]=i;
}
else
{
map.put(nums[i],i);
}
}
return arr;
}
}