题目链接:https://leetcode.com/problems/shuffle-an-array/
题目:
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle();
Subscribe to see which companies asked this question
思路:
使用 http://blog.csdn.net/yeqiuzs/article/details/52141124 中实现的数据结构,每次shuffle时 先获取初始集合一个随机数并删除,直至集合为空,一次shuffle完成,完成后需要恢复该存储集合的数据结构。 时间复杂度shuffle方法 O(n),reset方法O(n),构造方法O(n)。
这题我做复杂了。。不要这么做。。
最简单的方法是对数组做n次随机交换。。
算法:
public class Solution {
RandomizedSet rm;
int nums[];
public Solution(int[] nums) {
rm = new RandomizedSet();
this.nums = nums;
for (int i=0;i<nums.length;i++) {
rm.insert(nums[i]);
}
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
rm = new RandomizedSet();
for (int i=0;i<nums.length;i++) {
rm.insert(nums[i]);
}
return nums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
RandomizedSet tmp = new RandomizedSet();
int[] res = new int[rm.vals.size()];
for (int i = 0; i < res.length; i++) {
res[i] = rm.getRandom();
rm.remove(res[i]);
tmp.insert(res[i]);
}
rm = tmp;
return res;
}
class RandomizedSet {
/** Initialize your data structure here. */
public RandomizedSet() {
}
List<Integer> vals = new ArrayList<Integer>();
Map<Integer, Integer> val2idx = new HashMap<Integer, Integer>();
/**
* Inserts a value to the set. Returns true if the set did not already
* contain the specified element.
*/
public boolean insert(int val) {
if (val2idx.containsKey(val)) {
return false;
} else {
val2idx.put(val, val2idx.size());
vals.add(val);
return true;
}
}
/**
* Removes a value from the set. Returns true if the set contained the
* specified element.
*/
public boolean remove(int val) {
if (!val2idx.containsKey(val)) {
return false;
} else {
int idx = val2idx.remove(val);
if (idx < vals.size() - 1) {// 若删除的不是链表最后的元素
// 交换末尾元素和被删除元素
vals.set(idx, vals.get(vals.size() - 1));
val2idx.put(vals.get(vals.size() - 1), idx);
}
vals.remove(vals.size() - 1);
return true;
}
}
/** Get a random element from the set. */
Random r = new Random();
public int getRandom() {
return vals.get(r.nextInt(vals.size()));
}
}
}