第 406 场周赛

100352. 交换后字典序最小的字符串

枚举交换的位置

class Solution {
public:
    string getSmallestString(string s) {
        string res = s;
        for (int i = 1; i < s.size(); i++) {
            if (((s[i] - '0') % 2) == ((s[i - 1] - '0') % 2)) {
                swap(s[i], s[i - 1]);
                res = min(res, s);
                swap(s[i], s[i - 1]);
            }
        }
        return res;
    }
};

100368. 从链表中移除在数组中存在的节点

题目其实还是简单的,但是不熟悉面向对象的知识,加没有手写过链表导致各种 RE

/**
 * 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* nHead = new ListNode(-1);

    ListNode* modifiedList(vector<int>& nums, ListNode* head) {
        ListNode * lst = nHead;

        sort(nums.begin(), nums.end());
        for(auto it = head; it != nullptr; it = it -> next){
            int x = it -> val;
            auto pos = lower_bound(nums.begin(), nums.end(), x);
            if( pos != nums.end() and *pos == x) continue;
            lst -> next = new ListNode(x);
            lst = lst -> next;
        }
        nHead = nHead -> next;
        return nHead;
    }
};

其实我是知道,对于这种操作用带头结点的单链表很好实现。但是这个不带头确实不好处理。

学习了一下大佬的写法,感觉还是要学习一次现代 C++的规范了。

/**
 * 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* modifiedList(vector<int>& nums, ListNode* head) {
        unordered_set<int> st(nums.begin(), nums.end());
        ListNode dummy(0, head);
        ListNode *it = &dummy;
        while(it -> next != nullptr) {
            auto nxt = it -> next;
            if(st.contains(nxt -> val)) {
                it -> next = nxt -> next;
                delete nxt;
            }else {
                it = nxt;
            }
        }
        return dummy.next;
    }
};

100361. 切蛋糕的最小总开销 I/100367. 切蛋糕的最小总开销 II

按照代价对线进行排序。

class Solution {
public:
    long long minimumCost(int m, int n, vector<int>& horizontalCut, vector<int>& verticalCut) {
        vector<pair<long long,int>> a;
        for(auto i : horizontalCut)
            a.emplace_back(i, 0);
        for(auto i : verticalCut)
            a.emplace_back(i, 1);      
        vector<long long> cnt(2 , 1);
        ranges::sort(a, greater<>());
        long long res = 0;
        for(auto &[val , t] : a)
            res += val * cnt[t] , cnt[t ^ 1]  ++;
        return res;
    }
};
posted @ 2024-07-15 17:06  PHarr  阅读(2)  评论(0编辑  收藏  举报