-
Notifications
You must be signed in to change notification settings - Fork 1
/
1. Two Sum.java
70 lines (55 loc) · 1.69 KB
/
1. Two Sum.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
public int[] twoSum(int[] nums, int target) {
//BRUTE FORCE
/*
for(int i=0;i<nums.length;i++)
{
for(int j=0;j<nums.length;j++)
{
if(i!=j)
{
if(nums[i]+nums[j]==target)
{
return new int[]{i,j};
}
}
}
}
return new int[]{1,2};
*/
//OPTIMISED
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{
int complement = target - nums[i];
if(map.containsKey(complement))
{
int val = map.get(complement);
return new int[]{i,val};
}
map.put(nums[i],i);
}
return new int [] {1,2};
}
}
//python
//using hashmap / dictionary
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dictionary = {}
for i in range(0, len(nums)):
dictionary [nums[i]] = i
for i in range(0,len(nums)):
complement = target -nums[i]
if complement in dictionary and dictionary[complement] !=i:
return [i, dictionary[complement]]
//using one pass approach
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dictionary = {}
for i in range(0, len(nums)):
complement = target - nums[i]
if(complement in dictionary):
return [i,dictionary[complement]]
dictionary[nums[i]] = i
return null