当前位置:网站首页>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()的次数
边栏推荐
- Database course design of online assistant teaching platform for high school chemistry
- Mysql语句中的函数
- Getting started with solidity
- CryEngine技术
- AUTOSAR从入门到精通100讲(七十八)-AUTOSAR-DEM模块
- Qml类型:State 状态
- Legend how to configure multiple versions of wechat updates on one server
- 预约中,2022京东云产业融合新品发布会线上开启
- Apache POI实现Excel导入读取数据和写入数据并导出
- 6.2 function-parameters
猜你喜欢
随机推荐
Unity3D - 物体太远看不见的问题
About realizing page Jump of website in Servlet
This article takes you to understand the implementation of surround notification @around and final notification @after
[from_bilibili_DR_CAN][【Advanced控制理论】9_状态观测器设计][学习记录]
7.2-function-overloading
Legend how to configure multiple versions of wechat updates on one server
JS (foreach) return cannot end the function solution
C语言连连看秒杀辅助
直播预告:京东云DevOps与JFrog制品库的融合
How to add traffic statistics codes to the legendary Development Zone website
Arfoundation starts from zero 9-ar anchor
Handwritten student management system
CryEngine3 调试Shader方法
ARFoundation从零开始3-创建ARFoundation项目
小鲁客栈---预告篇
osg3.6.5编译freetype失败
Modification of annotation based three-tier project and the way of adding package scanning
6.3 references
Do you remember the process analysis and function implementation of post notification?
【[第一次写博客]Uda课程中的P控制器实现说明】









