Skip to content

Instantly share code, notes, and snippets.

@tanmay27vats
Created January 31, 2022 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanmay27vats/d95faddcddfc7d18aa6cc1b06e5c4da1 to your computer and use it in GitHub Desktop.
Save tanmay27vats/d95faddcddfc7d18aa6cc1b06e5c4da1 to your computer and use it in GitHub Desktop.
[PHP] Rotate Array - Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: nums …
class Solution {
/**
* @param Integer[] $nums
* @param Integer $k
* @return NULL
*/
function rotate(&$nums, $k) {
$count = 0;
$start = 0;
while ($count < count($nums)) {
$current = $start;
$prev = $nums[$start];
do {
$next = ($current + $k) % count($nums);
$temp = $nums[$next];
$nums[$next] = $prev;
$prev = $temp;
$current = $next;
$count++;
} while ($start != $current);
$start++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment