三次翻转实现数组元素的旋转

给定一个数组,将数组中的元素向右移动 k 个位置。

示例 1:

复制代码
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]

示例 2:

复制代码
输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释: 
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]

三次翻转法

  1. 将数组第i ( i∈[0,n-1-k] ) 项进行对称翻转
  2. 将数组第i ( i∈[n-k,n-1] ) 项进行对称翻转
  3. 将数组第i ( i∈[0,n-1] ) 项进行对称翻转

在lua源码中lua_rotate就是用这个方式实现旋转的:

Lua 复制代码
/*
** Reverse the stack segment from 'from' to 'to'
** (auxiliary to 'lua_rotate')
** Note that we move(copy) only the value inside the stack.
** (We do not move additional fields that may exist.)
*/
l_sinline void reverse (lua_State *L, StkId from, StkId to) {
  for (; from < to; from++, to--) {
    TValue temp;
    setobj(L, &temp, s2v(from));
    setobjs2s(L, from, to);
    setobj2s(L, to, &temp);
  }
}


/*
** Let x = AB, where A is a prefix of length 'n'. Then,
** rotate x n == BA. But BA == (A^r . B^r)^r.
*/
LUA_API void lua_rotate (lua_State *L, int idx, int n) {
  StkId p, t, m;
  lua_lock(L);
  t = L->top.p - 1;  /* end of stack segment being rotated */
  p = index2stack(L, idx);  /* start of segment */
  api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
  m = (n >= 0 ? t - n : p - n - 1);  /* end of prefix */
  reverse(L, p, m);  /* reverse the prefix with length 'n' */
  reverse(L, m + 1, t);  /* reverse the suffix */
  reverse(L, p, t);  /* reverse the entire segment */
  lua_unlock(L);
}
相关推荐
黎明smaly1 小时前
【排序】插入排序
c语言·开发语言·数据结构·c++·算法·排序算法
CCF_NOI.1 小时前
(普及−)B3629 吃冰棍——二分/模拟
数据结构·c++·算法
神的孩子都在歌唱2 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
艾莉丝努力练剑4 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
汤姆爱耗儿药10 小时前
专为磁盘存储设计的数据结构——B树
数据结构·b树
许小燚18 小时前
线性表——双向链表
数据结构·链表
qqxhb20 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
晚云与城20 小时前
【数据结构】顺序表和链表
数据结构·链表
FirstFrost --sy21 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Yingye Zhu(HPXXZYY)1 天前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法