14. 日常算法

1. 面试题 02.04. 分割链表

题目来源

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你不需要 保留 每个分区中各节点的初始相对位置。

c 复制代码
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* left = head;
        ListNode* right = head;
        while (right){
            if (right->val < x){
                std::swap(left->val, right->val);
                left = left->next;
            }
            right = right->next;
        }
        return head;
    }
};

2. LCR 170. 交易逆序对的总数

题目来源

在股票交易中,如果前一天的股价高于后一天的股价,则可以认为存在一个「交易逆序对」。请设计一个程序,输入一段时间内的股票交易记录 record,返回其中存在的「交易逆序对」总数。

示例 1:

输入:record = [9, 7, 5, 4, 6]

输出:8

解释:交易中的逆序对为 (9, 7), (9, 5), (9, 4), (9, 6), (7, 5), (7, 4), (7, 6), (5, 4)。

c 复制代码
class Solution {
public:
    void MergeSort(vector<int>& record, int left, int right, vector<int>& temp, int& ret){
        if (left >= right) return;
        int mid = left + (right - left) / 2;
        MergeSort(record, left, mid, temp, ret);
        MergeSort(record, mid + 1, right,  temp, ret);
        int k = left, l = left, r = mid + 1;
        while (l <= mid && r <= right){
            if (record[l] > record[r]){
                ret += mid - l + 1;
                temp[k++] = record[r++];
            }else{
                temp[k++] = record[l++];
            }
        }
        while (l <= mid) temp[k++] = record[l++];
        while (r <= right) temp[k++] = record[r++];

        for (int i = left; i <= right; i++){
            record[i] = temp[i];
        }

    }
    int reversePairs(vector<int>& record) {
        vector<int> temp;
        int ret = 0;
        int n = record.size();
        temp.resize(n);
        MergeSort(record, 0, n - 1, temp, ret);
        return ret;
    }
};
相关推荐
不穿格子的程序员10 分钟前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng1 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng1 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
2301_800399721 小时前
stm32 printf重定向到USART
java·stm32·算法
顾安r2 小时前
11.15 脚本算法 加密网页
服务器·算法·flask·html·同态加密
前端小L2 小时前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿3 小时前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
元亓亓亓3 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
2401_841495643 小时前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——寻找数组的中心下标
算法·leetcode·职场和发展·结构与算法