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

给定一个数组,将数组中的元素向右移动 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);
}
相关推荐
Lsk_Smion4 小时前
力扣实训 _ [102].层序遍历--前序--后续_递归与非递归的实现
数据结构·算法·leetcode
Lsk_Smion5 小时前
力扣实训 _ [25].K个一组链表
数据结构·链表
小欣加油6 小时前
leetcode3751 范围内总波动值I
java·数据结构·c++·算法·leetcode
V搜xhliang02468 小时前
临床科研新范式:从选题到投稿,AI智能体如何接管全流程?
运维·数据结构·人工智能·算法·microsoft·数据挖掘·自动化
梦想的颜色9 小时前
MySQL 查询性能核武器
运维·服务器·数据结构·数据库·mysql
八解毒剂10 小时前
查找-从二分查找到二叉排序树
数据结构·c++·算法
_日拱一卒11 小时前
LeetCode:78子集
数据结构·算法·leetcode·职场和发展
東隅已逝,桑榆非晚13 小时前
数据结构:算法效率与复杂度分析详解
数据结构·笔记·算法
半夜修仙13 小时前
分治思想对数组进行排序-归并排序
数据结构·算法·排序算法
小欣加油14 小时前
leetcode3635 最早完成陆地和水上游乐设施的时间II
数据结构·c++·算法·leetcode