给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
实现 Solution class:
- Solution(int[] nums) 使用整数数组 nums 初始化对象
- int[] reset() 重设数组到它的初始状态并返回
- int[] shuffle() 返回数组随机打乱后的结果
思路:
- 总思路:
- 应用题,很简单reset函数应该为重置,直接返回初始的数组即可
- shuttle为随机生成排序数组,只需要随机打乱即可。
class Solution {
private originalArr: number[];
constructor(nums: number[]) {
this.originalArr = nums;
}
reset(): number[] {
return this.originalArr;
}
shuffle(): number[] {
let numbers = this.originalArr.slice();
for(let i = 1;i < numbers.length;i++){
let index = Math.floor(Math.random()*(i+1));
let temp = numbers[i];
numbers[i] = numbers[index];
numbers[index] = temp;
}
return numbers;
}
}
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/