Leetcode 384 | Shuffle an Array

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Approach 1:

public int[] shuffle() {
int[] result = num.clone();
for(int i=num.length-1;i>=0;i--){
int r = random.nextInt(i+1);
int a = result[i];
result[i]=result[r];
result[r]=a;
}
return result;
}

Approach 2:

public int[] shuffle() {
int[] result = num.clone();
for(int i=0;i<num.length;i++){
int r = random.nextInt(i+1);
int a = result[i];
result[i]=result[r];
result[r]=a;
}
return result;
}

harshvashishtha
Автор

Leetcode 384 full sol:

private Random random;
public Solution(int[] nums) {
this.num=nums;
this.random= new Random();
}

public int[] reset() {
return num;

}

public int[] shuffle() {
int[] result = num.clone();
// for(int i=num.length-1;i>=0;i--){
// int r = random.nextInt(i+1);
// int a = result[i];
// result[i]=result[r];
// result[r]=a;
// }

for(int i=0;i<num.length;i++){
int r = random.nextInt(i+1);
int a = result[i];
result[i]=result[r];
result[r]=a;
}

return result;
}
}

harshvashishtha
visit shbcf.ru