Skip to content

Commit b4a1c56

Browse files
Created TwoNum
1 parent eaa02af commit b4a1c56

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Arrays/TwoSum.cpp

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
3+
4+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
5+
6+
You can return the answer in any order.
7+
8+
9+
10+
Example 1:
11+
12+
Input: nums = [2,7,11,15], target = 9
13+
Output: [0,1]
14+
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
15+
Example 2:
16+
17+
Input: nums = [3,2,4], target = 6
18+
Output: [1,2]
19+
20+
Constraints:
21+
22+
2 <= nums.length <= 104
23+
-109 <= nums[i] <= 109
24+
-109 <= target <= 109
25+
Only one valid answer exists.
26+
*/
27+
#include<bits/stdc++.h>
28+
using namespace std;
29+
vector<int> twoSum(vector<int>& nums, int target) {
30+
map<int,int> m;
31+
vector<int> v;
32+
for(int i=0;i<nums.size();i++)
33+
{
34+
if(m.find(target-nums[i])!=m.end())
35+
{
36+
v.push_back(m[target-nums[i]]);
37+
v.push_back(i);
38+
return v;
39+
}
40+
m[nums[i]]=i;
41+
}
42+
return v;
43+
}
44+
int main(){
45+
vector<int> nums;//to store elements
46+
int n,element,target;
47+
cin>>n;
48+
for (int i = 0; i < n; i++)
49+
{
50+
cin>>element;
51+
nums.push_back(element);//storing the elements
52+
}
53+
cin>>target;
54+
vector<int> result=twoSum(nums,target);
55+
for (int i = 0; i < result.size(); i++)
56+
{
57+
cout<<result[i]<<",";//print the elements
58+
}
59+
60+
return 0;
61+
}

0 commit comments

Comments
 (0)