diff --git a/src/main/java/leetcode/editor/cn/RotateArray.java b/src/main/java/leetcode/editor/cn/RotateArray.java new file mode 100644 index 0000000..63292e4 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/RotateArray.java @@ -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) + +} \ No newline at end of file diff --git a/src/main/java/leetcode/editor/cn/RotateArray.md b/src/main/java/leetcode/editor/cn/RotateArray.md new file mode 100644 index 0000000..49d431e --- /dev/null +++ b/src/main/java/leetcode/editor/cn/RotateArray.md @@ -0,0 +1,46 @@ +

给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

+ +

 

+ +

进阶:

+ + + +

 

+ +

示例 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]
+ +

 

+ +

提示:

+ + + + +
Related Topics
  • 数组
  • 数学
  • 双指针
  • \n
  • 👍 1003
  • 👎 0
  • \ No newline at end of file