Facile 0 résolus 0 % de réussite

Rotate Array

Rotate a list to the right by some steps.

Ce que vous allez apprendre

  • Shift elements with index arithmetic
  • Reduce large rotations with modulo
  • Build a rotated copy of a list

Problème

Afficher la traduction

Rotate the list to the right by steps positions: the last element moves to the front, steps times.

Implement rotate_right(numbers, steps).

Input

numbers: The list of integers. steps: How many positions to rotate.

Output

Return the rotated list.

Contraintes

0 ≤ length ≤ 100,000; 0 ≤ steps ≤ 10⁹

Exemples

Exemple 1
Entrée :
numbers = [1, 2, 3, 4, 5]
steps = 2

Sortie attendue :
expected = [4, 5, 1, 2, 3]
Entrée :
std::vector<long long> numbers = {1, 2, 3, 4, 5};
long long steps = 2;

Sortie attendue :
std::vector<long long> expected = {4, 5, 1, 2, 3};
Entrée :
long[] numbers = new long[] {1, 2, 3, 4, 5};
long steps = 2;

Sortie attendue :
long[] expected = new long[] {4, 5, 1, 2, 3};

Explication

Two right rotations: [5, 1, 2, 3, 4], then [4, 5, 1, 2, 3].

Exemple 2
Entrée :
numbers = [1, 2, 3]
steps = 3

Sortie attendue :
expected = [1, 2, 3]
Entrée :
std::vector<long long> numbers = {1, 2, 3};
long long steps = 3;

Sortie attendue :
std::vector<long long> expected = {1, 2, 3};
Entrée :
long[] numbers = new long[] {1, 2, 3};
long steps = 3;

Sortie attendue :
long[] expected = new long[] {1, 2, 3};

Explication

Rotating by the length brings the list back: [1, 2, 3].

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

A rotation by the list length changes nothing, so only the remainder matters.

Indice 2

Think of splitting the list near the end and moving that tail to the front.

Indice 3

Handle very large step counts by reducing them before rearranging.

Complexité attendue

O(n) time, O(n) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.