From cfc819b78c5ef8a8296d7dd04f98f20c41f9d1f8 Mon Sep 17 00:00:00 2001 From: Harshey Patnam <64657596+HarsheyP@users.noreply.github.com> Date: Thu, 5 Aug 2021 18:37:25 +0530 Subject: [PATCH] 3. Two Sum --- Hash Table/C++/3_Two_Sum.cpp | 119 +++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 Hash Table/C++/3_Two_Sum.cpp diff --git a/Hash Table/C++/3_Two_Sum.cpp b/Hash Table/C++/3_Two_Sum.cpp new file mode 100644 index 0000000..7fec7c3 --- /dev/null +++ b/Hash Table/C++/3_Two_Sum.cpp @@ -0,0 +1,119 @@ +/* + +Problem: Two Sum + +Description: +Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. +It is assumed that each input would have exactly one solution, and the same element is not used twice. + +This solution returns the indices of the array nums that sum up to obtain target in random order. + +Note: +2 <= nums.length <= 104 +-109 <= nums[i] <= 109 +-109 <= target <= 109 +Only one valid answer exists. + +*/ + +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector twoSum(vector& nums, int target) { + vector ans; + int l; + l=nums.size(); // l->size of the input array. + + + for(int i=0;i<(l-1);i++) { // This loop i goes from 0 to l-1. + for(int j=(i+1);j>t; // Number of testcases. + + for(int tc=0;tc>sz; //Size of the input array + + vector ar(sz); + + cout<<"Enter array values: "; + // Array values + for(int a=0;a>ar[a]; + } + + // Target + cout<<"Enter target: "; + int tar; + cin>>tar; + + vector answer; + + answer=s->twoSum(ar,tar); + + // Outputs the answer + cout<<"Output: "; + for(int o=0;o<(answer.size());o++) { + cout< Number of testcases +4 2 7 11 15 9 -> First testcase. +3 3 2 4 6 +2 3 3 6 + +SAMPLE OUTPUT: (Exclusive of interactive statements) +0 1 +1 2 +0 1 + +Explanation: +Testcase 1: +Input array(say nums): [2 7 11 15]. Target=9 +Output array: [0 1] which represent the indices of the input array that sum up to the target i.e., nums[0]+nums[1]=9 (Because 2+7=9). + +Same for all the testcases. + +Time Complexity: O(n^2) +n = Size of the input array + +*/