189:旋转数组

This commit is contained in:
huangge1199@hotmail.com 2021-07-08 22:58:52 +08:00
parent 656d6ba79d
commit adccc07d61
2 changed files with 118 additions and 0 deletions

View File

@ -0,0 +1,72 @@
//给定一个数组将数组中的元素向右移动 k 个位置其中 k 是非负数
//
//
//
// 进阶
//
//
// 尽可能想出更多的解决方案至少有三种不同的方法可以解决这个问题
// 你可以使用空间复杂度为 O(1) 原地 算法解决这个问题吗
//
//
//
//
// 示例 1:
//
//
//输入: nums = [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:
//
//
//输入nums = [-1,-100,3,99], k = 2
//输出[3,99,-1,-100]
//解释:
//向右旋转 1 : [99,-1,-100,3]
//向右旋转 2 : [3,99,-1,-100]
//
//
//
// 提示
//
//
// 1 <= nums.length <= 2 * 104
// -231 <= nums[i] <= 231 - 1
// 0 <= k <= 105
//
//
//
//
// Related Topics 数组 数学 双指针
// 👍 1003 👎 0
package leetcode.editor.cn;
//189:旋转数组
class RotateArray{
public static void main(String[] args) {
//测试代码
Solution solution = new RotateArray().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public void rotate(int[] nums, int k) {
int length = nums.length;
int temp[] = new int[length];
for (int i = 0; i < length; i++) {
temp[i] = nums[i];
}
for (int i = 0; i < length; i++) {
nums[(i + k) % length] = temp[i];
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,46 @@
<p>给定一个数组,将数组中的元素向右移动 <code>k</code><em> </em>个位置,其中 <code>k</code><em> </em>是非负数。</p>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。</li>
<li>你可以使用空间复杂度为 O(1) 的 <strong>原地 </strong>算法解决这个问题吗?</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> nums = [1,2,3,4,5,6,7], k = 3
<strong>输出:</strong> <code>[5,6,7,1,2,3,4]</code>
<strong>解释:</strong>
向右旋转 1 步: <code>[7,1,2,3,4,5,6]</code>
向右旋转 2 步: <code>[6,7,1,2,3,4,5]
</code>向右旋转 3 步: <code>[5,6,7,1,2,3,4]</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1,-100,3,99], k = 2
<strong>输出:</strong>[3,99,-1,-100]
<strong>解释:</strong>
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 2 * 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>0 <= k <= 10<sup>5</sup></code></li>
</ul>
<ul>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>数学</li><li>双指针</li></div></div>\n<div><li>👍 1003</li><li>👎 0</li></div>