Movatterモバイル変換


[0]ホーム

URL:


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

Commit9643a3b

Browse files
author
applewjg
committed
Next Permutation
Change-Id: Ia4fbd4ccd0ac09c4e29b27e467d1efcc46b42533
1 parentaea06ab commit9643a3b

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

‎NextPermutation.java

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 19, 2014
4+
Problem: Next Permutation
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/next-permutation/
7+
Notes:
8+
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
9+
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
10+
The replacement must be in-place, do not allocate extra memory.
11+
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
12+
1,2,3 -> 1,3,2
13+
3,2,1 -> 1,2,3
14+
1,1,5 -> 1,5,1
15+
16+
Solution: O(n)
17+
Processes: Take A = {1,3,2} as an example:
18+
1. Traverse from back to forth, find the turning point, that is A[i] = 3.
19+
2. Sort from the turning point to the end (A[i] to A[end]), so {3,2} becomes {2,3}.
20+
3. If i equals to 0, finish! Else, goto 4.
21+
4. Let j = i, search from A[j] to A[end] to find the first elem which is larger than A[i-1], '2' here.
22+
5. Swap the elem A[j] with A[i-1].
23+
Finally, the next permutation is {2,1,3}.
24+
*/
25+
26+
publicclassSolution {
27+
publicvoidnextPermutation_1(int[]num) {
28+
intlast =num.length -1;
29+
inti =last;
30+
while (i >0 &&num[i -1] >=num [i]) --i;
31+
if (i ==0) {
32+
for (intl =0,r =last;l <r; ++l, --r) {
33+
inttmp =num[l];
34+
num[l] =num[r];
35+
num[r] =tmp;
36+
}
37+
return;
38+
}
39+
for (intj =last;j >=i; --j) {
40+
if (num[j] >num[i-1]) {
41+
inttmp =num[j];
42+
num[j] =num[i-1];
43+
num[i-1] =tmp;
44+
for (intl =i,r =last;l <r; ++l, --r) {
45+
intt =num[l];
46+
num[l] =num[r];
47+
num[r] =t;
48+
}
49+
return;
50+
}
51+
}
52+
}
53+
publicvoidnextPermutation_2(int[]num) {
54+
intlast =num.length -1;
55+
inti =last;
56+
while (i >0 &&num[i -1] >=num [i]) --i;
57+
for (intl =i,r =last;l <r; ++l, --r) {
58+
num[l] =num[l] ^num[r];
59+
num[r] =num[l] ^num[r];
60+
num[l] =num[l] ^num[r];
61+
}
62+
if (i ==0) {
63+
return;
64+
}
65+
intj =i;
66+
while (j <=last &&num[i-1] >=num[j]) ++j;
67+
num[i-1] =num[i-1] ^num[j];
68+
num[j] =num[i-1] ^num[j];
69+
num[i-1] =num[i-1] ^num[j];
70+
}
71+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp