public class Solution {
    private int[] nums;
        private Random random;

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

        /** Resets the array to its original configuration and return it. */
        public int[] Reset()
        {
            return nums;
        }

        /** Returns a random shuffling of the array. */
        public int[] Shuffle()
        {
            if (nums == null)
            {
                return null;
            }
            int[] a = (int[])nums.Clone();
            for (int j = 1; j < a.Length; j++)
            {
                int i = random.Next(j + 1);
                Swap(a, i, j);
            }
            return a;
        }

        private void Swap(int[] a, int i, int j)
        {
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int[] param_1 = obj.Reset();
 * int[] param_2 = obj.Shuffle();
 */

https://leetcode.com/problems/shuffle-an-array/#/description

posted on 2017-05-10 21:00  Sempron2800+  阅读(128)  评论(0编辑  收藏  举报