当前位置:网站首页>365天挑战LeetCode1000题——Day 035 每日一题 + 二分查找 13
365天挑战LeetCode1000题——Day 035 每日一题 + 二分查找 13
2022-07-29 05:08:00 【ShowM3TheCode】
文章目录
1260. 二维网格迁移

首刷自解
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int m = grid.size();
int n = grid[0].size();
k %= m * n;
for (int i = 0; i < k; i++) {
int tmp = grid[m - 1][n - 1];
for (int j = m - 1; j >= 0; j--) {
for (int k = n - 1; k >= 0; k--) {
if (j == 0 && k == 0) break;
if (k == 0) grid[j][k] = grid[j - 1][n - 1];
else grid[j][k] = grid[j][k - 1];
}
}
grid[0][0] = tmp;
}
return grid;
}
};
算法复杂度: O ( i ∗ m ∗ n ) O(i * m * n) O(i∗m∗n), 其中i是k取模m*n
更好的方法是一维展开,算出元素下一个要去的位置
528. 按权重随机选择

首刷自解
class Solution {
public:
int sums;
vector<int> prefix;
Solution(vector<int>& w) {
sums = 0;
for (const auto& weight : w) {
sums += weight;
prefix.push_back(sums);
}
}
int pickIndex() {
int random = rand() % sums + 1;
auto it = lower_bound(prefix.begin(), prefix.end(), random);
return it - prefix.begin();
}
};
/** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(w); * int param_1 = obj->pickIndex(); */
算法复杂度: O ( n + k ∗ l o g ( n ) ) O(n + k * log(n)) O(n+k∗log(n)),k是调用pickIndex()的次数
边栏推荐
- [file download] easyexcel quick start
- 来!看排名一年上升16位的ClickHouse,如何在京东落地实践
- 小白高薪捷径-Qt开发游戏—贪吃蛇
- Helm chart for Kubernetes
- Arfoundation starts from scratch 8-geospatial API (geospatial) development
- 玩家访问网站自动弹窗加QQ群方法以及详细代码
- Mysql语句中的函数
- Webrtc audio anti weak network technology (Part 2)
- QT学习:使用JSON/XML等非ts文件实现多语言国际化
- Young freshmen yearn for more open source | here comes the escape guide from open source to employment!
猜你喜欢
随机推荐
基于注解的三层项目的改造及添加包扫描的方式
Qml类型:MouseArea
直播预告|如何节省30%人工成本,缩短80%商标办理周期?
How to add a map to the legendary server
MySQL sorts the queried result set according to the specified sequence
Arfoundation starts from zero 9-ar anchor
The latest tank battle 2022 - Notes on the whole development -2
Young freshmen yearn for more open source | here comes the escape guide from open source to employment!
Getting started with arfoundation tutorial 10- plane detection and placement
浅谈AspectJ框架
Rimworld通过SteamCMD上传创意工坊的方法
"Invisible Bridge" built in the free trade economy: domestic products and Chinese AI power
ARFoundation从零开始3-创建ARFoundation项目
AUTOSAR from introduction to proficiency 100 lectures (78) -autosar-dem module
Cache penetration, cache breakdown, cache avalanche and Solutions
SQL log
Mysql的自连接和联合查询
来!看排名一年上升16位的ClickHouse,如何在京东落地实践
CryEngine5 Shader调试
C语言函数实现输出I love you









