189. Rotate Array

本文解析了LeetCode上旋转数组问题的解决思路,包括直接使用新数组存储答案的暴力解法,以及满足O(1)空间复杂度要求的循环移动解法。详细讨论了循环移动中避免死循环的方法,并提供了完整的C++代码实现。
  1. 题目:https://leetcode.com/problems/rotate-array/
  2. 思路:
    1. 暴力,直接新new一个数组来存储答案,求出旋转后的index,放置元素即可
    2. 但是题目要求O(1)的空间,那就只能循环移动,a放在b,b放在c,c放在d
    1. 循环移动可能会移动到最开始的位置【死循环】,比如6个数字,移动3格,那需要移动3个循环【0移动到3,3移动到0;1移动到4,4移动到1;2移动到5,5移动到2】
  3. 代码
    class Solution {
    public:
        void rotate(vector<int>& nums, int k) {
            int len = nums.size();
            int next_temp;
            int index = 0;
            int next_index;
            if (len <= 1 || k%len==0)
                return;
            int temp = nums[0];
            int start_index = 0;
            for (int i = 0; i < len; i++) {
                next_index = (index+k)%len;
                next_temp = nums[next_index];
                nums[next_index] =temp;
                temp = next_temp;
                index = next_index;
                if (index == start_index) {
                    index = (index+1)%len;
                    temp = nums[index];
                    start_index = index;
                }
            }
            
        }
    };

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值