[Codility] Lesson2. CyclicRotation (C++)

2021. 2. 22. 21:29·코딩 테스트
728x90

🔮문제

An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).

The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

Write a function:

vector<int> solution(vector<int> &A, int K);

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given

A = [3, 8, 9, 7, 6] K = 3

the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]

[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]

[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]

 

🔮풀이

A 벡터의 마지막 원소를 pop 한 후 맨 앞에 insert를 해주었다.

이 과정을 K번 만큼 반복 수행.

예외처리 !!!! A 벡터가 비어있을 경우를 생각해야했다.


🔮코드

#include <algorithm>

vector<int> solution(vector<int> &A, int K) {
    //A벡터의 원소가 없으면 그대로 A 리턴
    if(A.size() == 0)
        return A;

    while(K--){
        int x = A.back();
        A.pop_back();
        A.insert(A.begin(), x);
    }
    return A;
  }
728x90

'코딩 테스트' 카테고리의 다른 글

[Codility] Lesson3. FrogJmp (C++)  (0) 2021.02.23
[Codility] Lesson1. BinaryGap (C++)  (0) 2021.02.23
[Codility] Lesson2. OddOccurrencesInArray (C++)  (0) 2021.02.22
[프로그래머스] 단어 변환 (C++)  (0) 2021.02.18
[프로그래머스] 가장 먼 노드 (C++)  (0) 2021.02.18
'코딩 테스트' 카테고리의 다른 글
  • [Codility] Lesson3. FrogJmp (C++)
  • [Codility] Lesson1. BinaryGap (C++)
  • [Codility] Lesson2. OddOccurrencesInArray (C++)
  • [프로그래머스] 단어 변환 (C++)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자바
    리트코드
    금융용어
    codility
    Python
    네트워크
    Kotlin
    C++
    스프링
    쿠버네티스
    카카오코테
    스프링부트
    자료구조
    CodingTest
    LeetCode
    프로그래머스
    springboot
    pythoncodingtest
    코딩
    코테
    코테공부
    db
    Spring
    코딜리티
    kafka
    java
    MySQL
    코딩테스트
    알고리즘
    이분탐색
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[Codility] Lesson2. CyclicRotation (C++)
상단으로

티스토리툴바