ys memos

Blog

leetcode384 shuffle an arrayの解説


leetcode

2021/07/23


コンストラクタに与えられた配列のシャッフル配列か元配列を返すクラスを設計する問題


コンストラクタで,元配列をプライベート変数に保存.

メソッド毎に,「配列をそのまま返す」「シャッフルして返す」とする.


main.cpp
class Solution {
  private:
    vector<int> data_;
  public:
  Solution(vector<int>& nums): data_{nums} {}

  /** Resets the array to its original configuration and return it. */
  vector<int> reset() {
    return data_;
  }

  /** Returns a random shuffling of the array. */
  vector<int> shuffle() {
    vector<int> output (data_);
    std::random_shuffle(output.begin(), output.end());
    return output;
  }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(nums);
 * vector<int> param_1 = obj->reset();
 * vector<int> param_2 = obj->shuffle();
 */


privateは無くても問題ないが,個人的にprivateは明示的に書きたいので,書いている.

class Solution {
  private:
    vector<int> data_;

与えられた配列をプライベート変数に保存する.

  public:
  Solution(vector<int>& nums): data_{nums} {}

プライベート変数をそのまま返す.

  vector<int> reset() {
    return data_;
  }

std::random_shuffle()を使って配列をシャッフルして返す.

  vector<int> shuffle() {
    vector<int> output (data_);
    std::random_shuffle(output.begin(), output.end());
    return output;
  }

};

std::random_shuffleはほとんど使ってこなかったので,この機会に使えて満足.


関連タグを探す