Skip to content

Four more Leetcode problems #9

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

Open
wants to merge 5 commits into
base: master
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
27 changes: 27 additions & 0 deletions Leetcode/19-remove-nth-node-from-end-of-list.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* p1=head,*p2=head;
for(int i=0; i<n; i++) {
p2 = p2->next;
}
if (p2 == nullptr) return head->next;
while (p2->next != nullptr) {
p1 = p1->next;
p2 = p2->next;
}
auto tmp = p1-> next;
p1->next = tmp->next;
return head;
}
};
27 changes: 27 additions & 0 deletions Leetcode/287-find-the-duplicate-number.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
public:
/*
Solution explanation:
Short explanation: checkout turtle and rabbit algorithm on cycle detection
Complete explanation: TBD
*/
int findDuplicate(vector<int>& nums) {
int slow=nums[0],fast=nums[0];

while (true) {
slow = nums[slow];
fast = nums[nums[fast]];
if (slow == fast) {
// do while is that you?
break;
}
}
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}

return slow;
}
};
24 changes: 24 additions & 0 deletions Leetcode/41-first-missing-positive.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
for(int index=0; index < nums.size(); index++) {
if (nums[index] > 0 && nums[index] < nums.size() + 1) {
int tmp = nums[nums[index]-1];
nums[nums[index] - 1] = nums[index];
nums[index] = tmp;
}
}
for(int index=0; index < nums.size(); index++) {
while (nums[index] > 0 && nums[index] < nums.size() + 1) {
if (nums[nums[index] - 1] == nums[index]) break;
int tmp = nums[nums[index]-1];
nums[nums[index] - 1] = nums[index];
nums[index] = tmp;
}
}
for(int index=0; index < nums.size(); index++) {
if (nums[index]!=index+1) return index+1;
}
return nums.size() + 1;
}
};