File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed
Problem Solution/1) 2 sum (easy) Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ 1) Brute Force [O(n^2)]
2
+ class Solution {
3
+ public:
4
+ vector<int> twoSum(vector<int>& nums, int target) {
5
+ vector<int> ret;
6
+ int size = nums.size();
7
+ for(int i=0 ; i < size - 1 ;i++)
8
+ {
9
+ for(int j = i+1 ; j<size ; j++)
10
+ {
11
+ if(nums[i]+nums[j] == target)
12
+ {
13
+ ret.push_back(i);
14
+ ret.push_back(j);
15
+ return ret;
16
+ }
17
+ }
18
+ }
19
+ return ret;
20
+ }
21
+ };
22
+
23
+ 2) Hash Table [O(n)]
24
+ class Solution {
25
+ public:
26
+ vector<int> twoSum(vector<int>& nums, int target) {
27
+ vector<int> ret;
28
+ int size = nums.size();
29
+ int diff;
30
+ unordered_map<int,int>m;
31
+ for (int i=0 ; i<size ; i++)
32
+ {
33
+ diff = target - nums[i];
34
+ if(m.find(diff) != m.end() && m.find(diff) -> second != i )
35
+ {
36
+ ret.push_back(i);
37
+ ret.push_back(m.find(diff) -> second);
38
+ return ret;
39
+ }
40
+ m[nums[i]] = i;
41
+ }
42
+ return ret;
43
+ }
44
+ };
Original file line number Diff line number Diff line change
1
+ 1) Brute force
2
+ class Solution(object):
3
+ def twoSum(self, nums, target):
4
+ #Using Two pointers P1 and P2 to represent every possible pairs of the array.
5
+ for p1 in range(len(nums)):
6
+ for p2 in range(p1+1, len(nums)):
7
+ #If one of those pairs add together equal to the target return the answer else return None.
8
+ if nums[p1] + nums[p2] == target:
9
+ return [p1, p2]
10
+ return 'None'
You can’t perform that action at this time.
0 commit comments