leet-code/src/main/java/leetcode/editor/cn/RotateArray.java
huangge1199@hotmail.com adccc07d61 189:旋转数组
2021-07-08 22:58:52 +08:00

72 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给定一个数组,将数组中的元素向右移动 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)
}