Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Copy list with random pointers #190

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions C++/2Sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int,int> mp;
for(int i=0;i<nums.size();i++)
{
if(mp.find(target -nums[i]) != mp.end())
{
return {mp[target- nums[i]],i};
}
else
mp[nums[i]]=i;
}
return {};
}
};
36 changes: 36 additions & 0 deletions C++/4Sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target)
{
vector<vector<int>> res;
if(nums.size() < 4) return res;
set<vector<int>> hash;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 2; i++) {
for(int j = i + 1; j < nums.size() - 1; j++)
{
int left = j + 1;
int right = nums.size() - 1;
while(left < right)
{
int sum = nums[i] + nums[left] + nums[right] + nums[j];
if(sum == target && !hash.count({nums[i], nums[j], nums[left], nums[right]})) {
hash.insert({nums[i], nums[j], nums[left], nums[right]});
res.push_back({nums[i], nums[j], nums[left], nums[right]});
left++;
right--;
while(left < right && nums[left] == nums[left - 1])
left++;
while(left < right && nums[right] == nums[right + 1])
right--;
}
else if(target > sum)
left++;
else
right--;
}
}
}
return res;
}
};
36 changes: 36 additions & 0 deletions C++/Copy_Linkedlist_with_Random_Pointers.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Node {
public:
int val;
Node* next;
Node* random;

Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
class Solution {
public:
Node* copyRandomList(Node* head)
{
unordered_map<Node*,Node*> mp;
Node* copy = nullptr;
Node* original = head;
while(original != NULL)
{
copy = new Node(original->val);
mp[original] = copy;
original= original->next;
}
original = head;
while(original != NULL)
{
copy = mp[original];
copy->next = mp[original->next];
copy->random = mp[original->random];
original = original->next;
}
return mp[head];
}
};