365天挑战LeetCode1000题——Day 111 归并排序 I

合并两个排序的链表

在这里插入图片描述

代码实现

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode* mergeTwoLists(ListNode* left, ListNode* right) {// if one of the two is empty returnif (!left) return right;if (!right) return left;ListNode* head = new ListNode(-1);ListNode* traverse = head;while (left && right) {if (left->val < right->val) {traverse->next = new ListNode(left->val);left = left->next;}else {traverse->next = new ListNode(right->val);right = right->next;}traverse = traverse->next;}if (left) traverse->next = left;if (right) traverse->next = right;return head->next;}
};

合并K个升序链表

在这里插入图片描述

代码实现

/*** 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 {
private:ListNode* mergeTwoLists(ListNode* left, ListNode* right) {// if one of the two is empty returnif (!left) return right;if (!right) return left;ListNode* head = new ListNode(-1);ListNode* traverse = head;while (left && right) {if (left->val < right->val) {traverse->next = new ListNode(left->val);left = left->next;}else {traverse->next = new ListNode(right->val);right = right->next;}traverse = traverse->next;}if (left) traverse->next = left;if (right) traverse->next = right;return head->next;}
public:ListNode* mergeKLists(vector<ListNode*>& lists) {if (lists.empty()) return nullptr;vector<ListNode*> tmp;int n = -1;while (lists.size() > 1) {n = lists.size();tmp.clear();for (int i = 0; i < n; i += 2) {if (i < n - 1) {tmp.push_back(mergeTwoLists(lists[i], lists[i + 1]));}else {tmp.push_back(lists[i]);}}lists = tmp;// cout << lists.size() << endl;}return lists[0];}
};

剑指 Offer 51. 数组中的逆序对

在这里插入图片描述

代码实现

class Solution {
private:int mergeSort(vector<int>& nums, vector<int>& tmp, int l, int r) {if (l == r) return 0;int m = (l + r) >> 1;int count = mergeSort(nums, tmp, l, m) + mergeSort(nums, tmp, m + 1, r);int i = l, j = m + 1, pos = l;while (i <= m && j <= r) {if (nums[i] <= nums[j]) {tmp[pos] = nums[i];i++;count += j - m - 1;}else {tmp[pos] = nums[j];j++;}pos++;}while (i <= m) {tmp[pos++] = nums[i++];count += j - m - 1;}while (j <= r) {tmp[pos++] = nums[j++];}copy(tmp.begin() + l, tmp.begin() + r + 1, nums.begin() + l);return count;}
public:int reversePairs(vector<int>& nums) {if (nums.empty()) return {};int n = nums.size();vector<int> tmp(n);return mergeSort(nums, tmp, 0, n - 1);}
};


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部