Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b5e34ac

Browse files
committed
feat: add leetcode question 198
1 parent 2ea2dbe commit b5e34ac

File tree

1 file changed

+51
-0
lines changed
  • 00-code(源代码)/src/com/hi/dhl/algorithms/leetcode/_189/java

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.hi.dhl.algorithms.leetcode._189.java;
2+
3+
/**
4+
* <pre>
5+
* author: dhl
6+
* date : 2022年10月30日
7+
* desc :
8+
* </pre>
9+
*/
10+
class Solution {
11+
// 方法一
12+
public void rotate(int[] nums, int k) {
13+
int len = nums.length;
14+
k = k % len;
15+
int times = 1;
16+
// 数组的总交换次数是和数组长度相等的
17+
// 所以记录一下总的交换次数即可
18+
for (int i = 0; i < times; i++) {
19+
int pre = nums[i];
20+
int cur = i;
21+
int count = 0; // 记录每次循环的交换次数
22+
do {
23+
cur = (cur + k) % len;
24+
int holder = nums[cur];
25+
nums[cur] = pre;
26+
pre = holder;
27+
count++;
28+
} while (i != cur); // 是否回到原点
29+
times = len / count; // 剩余交换次数
30+
}
31+
}
32+
33+
// 方法二
34+
public void rotate2(int[] nums, int k) {
35+
int len = nums.length;
36+
k = k % len;
37+
swap(nums, 0, len - 1);
38+
swap(nums, 0, k - 1);
39+
swap(nums, k, len - 1);
40+
}
41+
42+
public void swap(int[] nums, int lo, int hi) {
43+
while (lo < hi) {
44+
int holder = nums[lo];
45+
nums[lo] = nums[hi];
46+
nums[hi] = holder;
47+
lo++;
48+
hi--;
49+
}
50+
}
51+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /