LoginSignup
1
0

More than 5 years have passed since last update.

【codility】Lesson 2: Arrays CyclicRotation

Last updated at Posted at 2018-06-02

subject

Lesson 2:Arrays CyclicRotation
配列AをK回右方向に回転させた時の、最終的な配列の要素の順番を求める問題。
例)
A = {3,8,9,7,6} K = 3の場合の答えは、A = {9,7,6,3,8}となる。
右方向に回転と言う表現にしているが、要するに配列の一番後ろの数字を配列の一番前に持っていくと考えるとわかりやすい。

submit

今回は、1回目のsubmitでscore87を出し、2回目でscore100。
配列が空の時の対応は、スコアに関連があるようで、

if(arrayLength == 0)
        return A;

ここのコードを付け加えてクリアしました。毎回、配列が空かどうかを確認するコードは入れようと思う。

スクリーンショット 2018-06-02 15.03.33.png

program

Point:vectorのpush_backとeraceを使ったところ
vectorの便利!!と心から思った。

cyclicRotation.cpp
#include<iostream>
#include<vector>
using namespace std;

vector<int> solution(vector<int> &A, int K) {
    int count  = 0; 
    int cyclic = 0;
    int arrayLength = A.size();

    if(arrayLength == 0)
        return A;
    else if (arrayLength < K)
        cyclic = arrayLength - (K % arrayLength);
    else
        cyclic = arrayLength - K;

    while (count < cyclic) {
        if (!A.empty()) {
            A.push_back(A[0]);
            A.erase(A.begin());
            count++;
        }
        else {
            break;
        }
    }
    return A;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0