题目如下:

Given a 2D grid of size n * m and an integer k. You need to shift the grid k times.

In one shift operation:

  • Element at grid[i][j] becomes at grid[i][j + 1].
  • Element at grid[i][m - 1] becomes at grid[i + 1][0].
  • Element at grid[n - 1][m - 1] becomes at grid[0][0].

Return the 2D grid after applying shift operation k times.

Example 1:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]

Example 2:

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]

Constraints:

  • 1 <= grid.length <= 50
  • 1 <= grid[i].length <= 50
  • -1000 <= grid[i][j] <= 1000
  • 0 <= k <= 100

解题思路:记grid的行数为row,列数为col,显然经过row*col次移动后和不移动效果是一样的,所以可以首先令k = k%(row*col)。剩下的k就是每一个元素需要移动的次数,我的方法是给grid的每个元素编号,从左到右,从上到下,依次为0,1,1....row*col - 1,这样方便计算。

代码如下:

class Solution(object):
def shiftGrid(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
row = len(grid)
col = len(grid[0])
k = k%(row * col)
res = [[0] * col for _ in range(row)]
for i in range(row):
for j in range(col):
inx = (i*col + j) + k
if inx >= (row*col):inx -= row*col
newrow = inx/col
newcol = inx%col
res[newrow][newcol] = grid[i][j]
return res

最新文章

  1. .NET Core的日志[5]:利用TraceSource写日志
  2. SE16N使用方案总结
  3. sql搜索like通配符的用法详解
  4. docker启动Mysql(转)
  5. Linux查看所有用户用什么命令
  6. 类图class的依赖关系
  7. CentOS 7安装squid代理服务器
  8. 帧动画的创建方式 - xml方式
  9. 『最短Hamilton路径 状态压缩DP』
  10. ef err
  11. 修改minifest使桌面软件支持高dpi
  12. 真正的Maven经常使用命令
  13. Cisco Common Service Platform Collector - Hardcoded Credentials(CVE-2019-1723)
  14. npm 包管理器的使用
  15. 短信验证登陆-中国网建提供的SMS短信平台
  16. 设置pip源头地址
  17. openerp 7.0接收陌生邮件名称显示乱码问题解决方法
  18. NIO概述及实例(时钟服务器)
  19. Servlet基础知识总结
  20. python selenium自动化测试之路(1)--分层测试概念、selenium工具介绍

热门文章

  1. 【C/C++】BOOST 线程完全攻略 - 基础篇
  2. 【神经网络与深度学习】如何在Caffe中配置每一个层的结构
  3. Linux 防火墙开放特定端口 (iptables)
  4. 2.更新YUM源
  5. python_0基础开始_day06
  6. 基于Keras的OpenAI-gym强化学习的车杆/FlappyBird游戏
  7. 如何用纯 CSS 创作一个精彩的彩虹 loading 特效
  8. 如何在万亿级别规模的数据量上使用Spark
  9. python之BeautifulSoup4
  10. 小P的架构生活(上)