Using Cyclic Replacements解决数组原址移动问题

Using Cyclic Replacement


void rotate(vector<int>& nums, int k) {
        int n=nums.size();
        k=k%n;
       int start;
       int count=0;
       for(start=0;count<n;start++)
       {
           int cur=start;
           int pre=nums[start];
           do{
               int next=(cur+k)%n;//下一个下标
               int tmp=nums[next];
                nums[next]=pre;//将上一个元素放到这个位置
                //更新pre,count,cur
               pre=tmp;
               cur=next;
               count++;
           }while(start!=cur);
       }
    }
变形:如果这里的数组移动,不是简单的反转,也要求利用O(1)的空间,怎么办?在论坛上看到这个题目,

Given a descending array A, reorder it to: Ln→L0→Ln-1→L1→Ln-2→L2→…
e.g. A = [7, 6, 5, 4, 3, 2, 1] → A = [1, 7, 2, 6, 3, 5, 4]

NOTICE: do this with only O(1) memory space and in O(n) time complexity.

只要加一个能正确得到next的函数即可。
<pre name="code" class="cpp">int nextone(int cur,int n)
{
if(cur<n/2)
return 1+cur*2;
else return (n-cur-1)*2;	
}
void reorder(vector<int>& nums){
int n=nums.size();
int start;
int count=0;
for(start=n-1;count<n;start--)
{
int cur=start;
int pre=nums[start];
do{
int next=nextone(cur,n);
int tmp=nums[next];
nums[next]=pre;
pre=tmp;
cur=next;
count++;
}while(start!=cur);
}
return;
}


 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值