diff --git a/Leetcode/19-remove-nth-node-from-end-of-list.cpp b/Leetcode/19-remove-nth-node-from-end-of-list.cpp new file mode 100644 index 0000000..6e7d816 --- /dev/null +++ b/Leetcode/19-remove-nth-node-from-end-of-list.cpp @@ -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; inext; + } + 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; + } +}; \ No newline at end of file diff --git a/Leetcode/234-palindrome-linked-list b/Leetcode/234-palindrome-linked-list.cpp similarity index 100% rename from Leetcode/234-palindrome-linked-list rename to Leetcode/234-palindrome-linked-list.cpp diff --git a/Leetcode/287-find-the-duplicate-number.cpp b/Leetcode/287-find-the-duplicate-number.cpp new file mode 100644 index 0000000..22842dd --- /dev/null +++ b/Leetcode/287-find-the-duplicate-number.cpp @@ -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& 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; + } +}; \ No newline at end of file diff --git a/Leetcode/41-first-missing-positive.cpp b/Leetcode/41-first-missing-positive.cpp new file mode 100644 index 0000000..52cc4b5 --- /dev/null +++ b/Leetcode/41-first-missing-positive.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int firstMissingPositive(vector& 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; + } +}; \ No newline at end of file