Leetcode 第 406 场周赛题解
Leetcode 第 406 场周赛题解
题目1:3216. 交换后字典序最小的字符串
思路
找到第一个 s[i] > s[i + 1],且它们奇偶性相同,交换它们。
代码
/*
* @lc app=leetcode.cn id=3216 lang=cpp
*
* [3216] 交换后字典序最小的字符串
*/
// @lc code=start
class Solution
{
public:
string getSmallestString(string s)
{
int n = s.size();
for (int i = 0; i < n - 1; i++)
{
if (s[i] > s[i + 1] && check(s[i] - '0', s[i + 1] - '0'))
{
swap(s[i], s[i + 1]);
return s;
}
}
return s;
}
// 辅函数
bool check(int a, int b)
{
return a % 2 == b % 2;
}
};
// @lc code=end
复杂度分析
时间复杂度:O(n),其中 n 是字符串 s 的长度。
空间复杂度:O(1)。
题目2:3217. 从链表中移除在数组中存在的节点
思路
集合 + 链表遍历。
代码
/*
* @lc app=leetcode.cn id=3217 lang=cpp
*
* [3217] 从链表中移除在数组中存在的节点
*/
// @lc code=start
/**
* 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> dict(nums.begin(), nums.end());
ListNode *dummy = new ListNode();
dummy->next = head;
ListNode *p = dummy;
while (p->next)
{
if (dict.contains(p->next->val))
p->next = p->next->next;
else
p = p->next;
}
return dummy->next;
}
};
// @lc code=end
复杂度分析
时间复杂度:O(n+m),其中 n 是数组 nums 的长度,m 是链表的长度。
空间复杂度:O(n),其中 n 是数组 nums 的长度。
题目3:3218. 切蛋糕的最小总开销 I
思路
对于两个数组horizontalCut和verticalCut,简称h和v,若v数组已经切了j次,则当切h[i]刀时,cost为h[i] * (j+1)。
很明显,要使总cost最小,对于两个数组,cost花费越大的那一行或者那一列,应该优先切除,因此先从大到小排序预处理。
代码
#
# @lc app=leetcode.cn id=3218 lang=python3
#
# [3218] 切蛋糕的最小总开销 I
#
# @lc code=start
class Solution:
def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int:
horizontalCut.sort(reverse=True)
verticalCut.sort(reverse=True)
m -= 1
n -= 1
@cache
def dfs(i, j):
if i == m and j == n:
return 0
if i == m:
return dfs(i, j + 1) + verticalCut[j] * (i + 1)
if j == n:
return dfs(i + 1 , j) + horizontalCut[i] * (j + 1)
return min(dfs(i, j + 1) + verticalCut[j] * (i + 1), dfs(i+ 1, j) + horizontalCut[i] * (j + 1))
return dfs(0, 0)
# @lc code=end
复杂度分析
时间复杂度:O(m2+n2+2*(m+n))。
空间复杂度:O(m2+n2+2*(m+n))。
题目4:3219. 切蛋糕的最小总开销 II
思路
谁的开销更大,就先切谁,并且这个先后顺序与切的次数无关。
代码
/*
* @lc app=leetcode.cn id=3219 lang=cpp
*
* [3219] 切蛋糕的最小总开销 II
*/
// @lc code=start
class Solution
{
public:
long long minimumCost(int m, int n, vector<int> &horizontalCut, vector<int> &verticalCut)
{
sort(horizontalCut.begin(), horizontalCut.end(), greater<int>());
sort(verticalCut.begin(), verticalCut.end(), greater<int>());
long long ans = 0;
int cnt_h = 1, cnt_v = 1;
int i = 0, j = 0;
while (i < m - 1 || j < n - 1)
{
if (j == n - 1 || i < m - 1 && horizontalCut[i] > verticalCut[j])
{
ans += horizontalCut[i++] * cnt_h; // 横切
cnt_v++; // 需要竖切的蛋糕块增加
}
else
{
ans += verticalCut[j++] * cnt_v; // 竖切
cnt_h++; // 需要横切的蛋糕块增加
}
}
return ans;
}
};
// @lc code=end
复杂度分析
时间复杂度:O(mlogm+nlogn),瓶颈在排序上。
空间复杂度:O(1)。