当前位置:网站首页>Leetcode weekly buckle race 296
Leetcode weekly buckle race 296
2022-06-10 03:53:00 【Time_ Limit】
Weekly portal

ranking 20, Big points !
Minimax game
Ideas : simulation , Modify in place
Time complexity : O ( n ∗ lg n ) \mathrel{O}({n*\lg n}) O(n∗lgn)
Spatial complexity : O ( n ) \mathrel{O}(n) O(n)
Only half of the elements are reserved for each round of operation , And each operation only depends on two adjacent elements , Independent of previous elements . Therefore, you can simulate the operation process on the original array . See code Notes for details .
class Solution {
public:
int minMaxGame(vector<int>& nums) {
while (nums.size() > 1) {
// Enumerate the subscripts of the new array i, from 0 To n/2
for (int i = 0; i*2 < nums.size(); i++) {
if (i&1) {
// The subscript of the new array is odd , Take the larger of the two
nums[i] = max(nums[i*2], nums[i*2+1]);
} else {
// The subscript of the new array is odd , Take the smaller of the two
nums[i] = min(nums[i*2], nums[i*2+1]);
}
}
// here nums It is already a new array , Only the first half of the elements are meaningful , Reset size .
nums.resize(nums.size()/2);
}
return nums[0];
}
};
Divide the array so that the maximum difference is K
Ideas : Sort , greedy , Double pointer
Time complexity : O ( n lg n ) \mathrel{O}(n\lg n) O(nlgn)
Spatial complexity : O ( n ) \mathrel{O}(n) O(n)
Let the smallest element in the whole array be x x x, Then place the value at [ x , x + k ] [x, x+k] [x,x+k] It is obviously optimal for the elements in the same sequence . For the remaining elements , The partitioning strategy still applies .
On the implementation , But first of all, I will nums Sort , Make the elements in the subsequence in nums Are all adjacent . Then use the double pointer to O ( n ) \mathrel{O}(n) O(n) The time complexity to get the answer .
class Solution {
public:
int partitionArray(vector<int>& nums, int k) {
// Sort in ascending order first , Make the elements of the subsequence in nums It's all adjacent .
sort(nums.begin(), nums.end());
// use anw Record answer . At the beginning of the , It has not been divided, so there is only one Sequence .
int anw = 1;
// pre Is the smallest element of the current subsequence nums Subscript in
// from pre To n enumeration i, Find the maximum value that can be put into the current sequence .
for (int pre = 0, i = 0; i < nums.size(); i++) {
if (nums[i] - nums[pre] > k) {
// Out of range , It shows that a new subsequence needs to be divided .
pre = i;
anw++;
}
}
return anw;
}
};
Replace elements in an array
Ideas : Hashtable
Time complexity : O ( n + m ) \mathrel{O}(n+m) O(n+m)
Spatial complexity : O ( n ) \mathrel{O}(n) O(n)
Because in the whole process , There are no duplicate elements in the array , So available unordered_map Save the mapping relationship between the element and its position during the modification process .
In every operation , The logic for updating the position of new and old elements is also clear :
- The new element is in the same position as the old element .
- Old element from
unordered_mapDelete from .
After modification , You can use unordered_map restructure nums.
class Solution {
public:
vector<int> arrayChange(vector<int>& nums, vector<vector<int>>& operations) {
unordered_map<int, int> pos;
// Initialize the mapping relationship between elements and positions
for (int i = 0; i < nums.size(); i++) {
pos[nums[i]] = i;
}
for (const auto &op : operations) {
// The new element is in the same position as the old element
pos[op[1]] = pos[op[0]];
// Delete old element
pos.erase(op[0]);
}
// Refactoring arrays
for (auto p : pos) {
nums[p.second] = p.first;
}
return nums;
}
};
Design a text editor
Ideas : simulation
Time complexity :
addText: O ( ∣ t e x t ∣ ) \mathrel{O}(|text|) O(∣text∣)deleteText: O ( k ) \mathrel{O}(k) O(k)cursorLeft: O ( k ) \mathrel{O}(k) O(k)cursorRight: O ( k ) \mathrel{O}(k) O(k)
Spatial complexity : O ( n ) \mathrel{O}(n) O(n), n n n During operation , The longest length a text can reach .
Use two strings prefix and suffix Store the data before and after the cursor respectively , The part after the cursor is stored in reverse order suffix.
such as ,leet|code Such a text ,prefix and suffix The data are as follows :
prefix = "leet"suffix = "edoc"
On the basis of the above storage methods , The four operations can be implemented as follows :
addText: Add toprefixThe tail .deleteText: DeleteprefixAt the end of the k k k Characters .cursorLeft: takeprefixAt the end of the k k k Characters are moved tosuffixThe tail .cursorRight: takesuffixAt the end of the k k k Characters are moved toprefixThe tail .
The complete code is as follows :
class TextEditor {
string prefix;
string suffix;
public:
TextEditor() {
}
void addText(string text) {
prefix.append(text.c_str(), text.size());
}
int deleteText(int k) {
if (k > prefix.size()) {
k = prefix.size();
}
prefix.resize(prefix.size()-k);
return k;
}
string cursorLeft(int k) {
while (k && prefix.size()) {
k--;
suffix.append(1, *prefix.rbegin());
prefix.resize(prefix.size()-1);
}
if (prefix.size() <= 10) {
return prefix;
}
return prefix.substr(prefix.size()-10);
}
string cursorRight(int k) {
while (k && suffix.size()) {
k--;
prefix.append(1, *suffix.rbegin());
suffix.resize(suffix.size()-1);
}
if (prefix.size() <= 10) {
return prefix;
}
return prefix.substr(prefix.size()-10);
}
};
/** * Your TextEditor object will be instantiated and called as such: * TextEditor* obj = new TextEditor(); * obj->addText(text); * int param_2 = obj->deleteText(k); * string param_3 = obj->cursorLeft(k); * string param_4 = obj->cursorRight(k); */
边栏推荐
- 【SingleShotMultiBoxDetector(SSD,单步多框目标检测)】
- 【从零开始搭建神经网络并将准确率提升至85%】
- 概率编程工具:TensorFlow Probability官方简介
- SSTI(模板注入) ——(8)
- Understanding of analog-to-digital conversion
- 基于用户行为的生物探针和智能验证码
- Ssti (injection de gabarit) - (7)
- [pytorch modifies the pre training model: there is little difference between the measured loading pre training model and the random initialization of the model]
- Where can I open a futures account? Is it safe to open an account online?
- MySQL——数据类型
猜你喜欢

【从零开始搭建神经网络并将准确率提升至85%】

Redis 核心技术与实战-实践篇读书笔记 20~终结

Pytorch CPU/GPU 安装方法。

【主流Nivida显卡深度学习/强化学习/AI算力汇总】

Dapr - what are the advantages of the microservice framework used by major manufacturers?

From ancient literature to cloud technology

RPC 实战与核心原理-进阶篇笔记

All MySQL collections from 0 to 1 are highly recommended

LeetCode 力扣周賽 296

RPC practice and core principles - Advanced notes
随机推荐
阿里云首次年度盈利,国内云厂商何时迎来集体回报期?
Monotone queue optimization DP example
汇编:关于函数完整流程的栈桢解析
【load dataset】
Dapr - what are the advantages of the microservice framework used by major manufacturers?
使用队列实现进程之间的数据共享
[summary of pytoch optimizer]
MySQL——安装
[pytorch pre training model modification, addition and deletion of specific layers]
QT window, viewport, logical coordinates, physical coordinates
[build a neural network from scratch and improve the accuracy to 85%]
SSTI(模板注入) ——(7)
Probabilistic programming tool: official introduction to tensorflow probability
"Chinese characteristics" of Web3
vulnhub——BILLU: B0X
35岁逃离北上广,40岁失业送外卖,中年人的“体面”在于投资自己
反欺诈体系与设备指纹
SSTI (template injection) - (7)
Opencv_ 100 questions_ Chapter I (1-5)
Business card wechat applet error version 2