classSolution{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. 按权重随机选择
首刷自解
classSolution{public:int sums;
vector<int> prefix;Solution(vector<int>& w){
sums =0;for(constauto& weight : w){
sums += weight;
prefix.push_back(sums);}}intpickIndex(){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()的次数