[384] 打乱数组
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
实现 Solution class:
- Solution(int[] nums) 使用整数数组 nums 初始化对象
- int[] reset() 重设数组到它的初始状态并返回
- int[] shuffle() 返回数组随机打乱后的结果
打乱的时候clone一个新的数组,然后打乱这个新的数组即可。
class Solution {
private int[] nums;
private Random random;
public Solution(int[] nums) {
this.nums = nums;
random = new Random();
}
//重置数组,就是返回之前的数组
public int[] reset() {
return nums;
}
//打乱数组
public int[] shuffle() {
if (nums == null) {
return null;
}
int[] clone = nums.clone();
for (int i = 0; i < clone.length; i++) {
int i1 = random.nextInt(i + 1);
swap(clone, i, i1);
}
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
水仙花
public class Shuixianghua {
List f(int start, int end) {
List<Integer> list = new ArrayList<>();
int j = 0;
for(int i = start; i <= end; i++) {
if(i == Math.pow(Math.floor(i / 100), 3) + Math.pow(Math.floor(i % 100 / 10), 3)
+ Math.pow(i % 100 % 10, 3)){
list.add(i);
}
}
return list;
}
}