Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 98e43be

Browse files
Two-sum-problem
1 parent 05cb2f8 commit 98e43be

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎two-sum.cpp‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution
2+
{
3+
public:
4+
vector<int> twoSum(vector<int> &nums, int target)
5+
{
6+
// Method 1: using BRute force method:
7+
// vector<int>ans;
8+
// for(int i =0;i<nums.size();i++){
9+
// for(int j= i+1;j<nums.size();j++){
10+
// if(nums[i]+nums[j]==target){
11+
// ans.push_back(i);
12+
// ans.push_back(j);
13+
// }
14+
// }
15+
// }
16+
// return ans;
17+
18+
// -----------------------------------------------------------
19+
20+
// METHOD 3: USING 2 FOR LOOPS:
21+
// vector<int>ans;
22+
// unordered_map<int,int>hash;
23+
// for(int i =0;i<nums.size();i++){
24+
// hash[nums[i]]=i;
25+
// }
26+
// for(int i=0;i<nums.size();i++){
27+
// int element = target - nums[i];
28+
// if(hash.count(element) && hash[element]!=i){
29+
// ans.push_back(i);
30+
// ans.push_back(hash[element]);
31+
// break;
32+
// }
33+
// }
34+
// return ans;
35+
36+
// ---------------------------------------------------
37+
// METHOD 2: USING unordered_map and 1 for loop:
38+
39+
unordered_map<int, int> hash;
40+
vector<int> ans;
41+
for (int i = 0; i < nums.size(); i++)
42+
{
43+
int element = target - nums[i];
44+
if (hash.count(element))
45+
{
46+
47+
ans.push_back(i);
48+
ans.push_back(hash[element]);
49+
}
50+
hash[nums[i]] = i;
51+
}
52+
53+
return ans;
54+
}
55+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /