Leetcode c++ solution

Question Link

https://leetcode.com/problems/two-sum/

Question

Approach

  1. Brute Force

We can check the pairs that sum to target in O(n2) by running two for loops and by checking them.

2. Another method will be using Hashmap

vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> m;
vector<int> v;
for(int i=0;i<nums.size();i++)
{

m[nums[i]]++;

}

if(m.find(target-nums[i])!=m.end())
{
v.push_back(m[target-nums[i]]);
v.push_back(i);
return v;
}

m[nums[i]]=i;
}
return v;

}

Time Complexity =O(n)

Thank you:)

--

--

I choose this question for my first article.Because, a lot of people stuck to figure that how to start blogging.

In medium,the only thing we have to do is in three steps.That is

  1. creating a medium account
  2. click on profile and select write a story
  3. Start writing:)

Then after you have finished the writing.click on publish button which is at the top of the page.

Actually,I have been thinking from so many days.If you were thinking to start writing..

Just start writing..Don’t think too much about it, just write some something you were fond of and putting it on Medium. It doesn’t cost you anything.Keep moving..

Thank you:)

--

--