Last active
August 29, 2015 14:23
-
-
Save HDegano/0df77976df978b22b93c to your computer and use it in GitHub Desktop.
Rotate Array with O(n) complexity and O(1) space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RotateArray { | |
public void rotate(int[] nums, int k) { | |
if(k > nums.length) k = k % nums.length; | |
reverse(nums, 0, nums.length); | |
reverse(nums, 0, k); | |
reverse(nums, k, nums.length); | |
} | |
private void reverse(int[] ar, int from, int upTo){ | |
if(upTo <= from) return; | |
int l = upTo - from; | |
int mid = (from + l /2); | |
for(int i = from, j = upTo - 1; i < mid && j >= mid ; i++, j--){ | |
int temp = ar[i]; | |
ar[i] = ar[j]; | |
ar[j] = temp; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment