---
# System prepended metadata

title: Algo｜Shuffle Array 演算法
tags: [Algo]

---

# Shuffle Array 演算法
- [384. Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/)
- https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
- 使用 swap 相較於依序取出 nums[i] 更有效率
    ```c++=
    void shuffle(vector<int> &nums) {
        int n = nums.size();
        for(int i=n-1;i>=0;i--){
            int id = rand() % (i+1);
            swap(nums[id], nums[i]);
        }
        return nums;
    }
    ```
    
