欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > LeetCode[中等] 189.轮转数组

LeetCode[中等] 189.轮转数组

2024/10/23 19:32:02 来源:https://blog.csdn.net/Theolulu/article/details/142303691  浏览:    关键词:LeetCode[中等] 189.轮转数组

给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。

思路

创建一个新数组,存储原数组旋转后的元素,然后将新数组中的元素复制回原数组。

public class Solution {public void Rotate(int[] nums, int k) {int length = nums.Length;int[] newNums = new int[length];for(int i = 0; i < length; i++)newNums[(i + k) % length] = nums[i];for(int i = 0; i < length; i++)nums[i] = newNums[i];}
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是数组 nums 的长度。需要遍历原数组 nums 一次对新数组 newNums 进行赋值,然后需要遍历新数组 newNums 一次将元素复制回原数组 nums。
  • 空间复杂度:O(n),其中 n 是数组 nums 的长度。需要创建一个长度为 n 的新数组 newNums。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com