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

Commit4e1241b

Browse files
add a solution for 384
1 parentad10724 commit4e1241b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_384.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,5 +74,43 @@ public int[] shuffle() {
7474
returnresult;
7575
}
7676
}
77+
78+
publicstaticclassSolution2 {
79+
/**
80+
* credit: https://leetcode.com/problems/shuffle-an-array/discuss/85958/First-Accepted-Solution-Java
81+
*/
82+
privateint[]nums;
83+
privateRandomrandom;
84+
85+
publicSolution2(int[]nums) {
86+
this.nums =nums;
87+
this.random =newRandom();
88+
}
89+
90+
/**
91+
* Resets the array to its original configuration and return it.
92+
*/
93+
publicint[]reset() {
94+
returnthis.nums;
95+
}
96+
97+
/**
98+
* Returns a random shuffling of the array.
99+
*/
100+
publicint[]shuffle() {
101+
int[]shuffled =this.nums.clone();
102+
for (inti =1;i <nums.length;i++) {
103+
intj =random.nextInt(i +1);
104+
swap(shuffled,i,j);
105+
}
106+
returnshuffled;
107+
}
108+
109+
privatevoidswap(int[]shuffled,inti,intj) {
110+
inttmp =shuffled[i];
111+
shuffled[i] =shuffled[j];
112+
shuffled[j] =tmp;
113+
}
114+
}
77115
}
78116

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
packagecom.fishercoder;
2+
3+
importcom.fishercoder.common.utils.CommonUtils;
4+
importcom.fishercoder.solutions._384;
5+
importorg.junit.Test;
6+
7+
publicclass_384Test {
8+
privatestatic_384.Solution2solution2;
9+
10+
@Test
11+
publicvoidtest1() {
12+
solution2 =new_384.Solution2(newint[]{1,2,3,4,5,6,7,8,9,10,11,12});
13+
CommonUtils.printArray(solution2.shuffle());
14+
}
15+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp