write once,run anywhere
  • Home
  • Tags
  • Archives

LeetCode [189] Rotate Array

Contents

  • Questions
  • Coding
    • Java
    • python

Questions¶

Difficulty: Easy

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, 
the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

Hint: Could you do it in-place with O(1) extra space?

Coding¶

Java¶

public class Solution {
    public void swap(int[] array, int a, int b) {
        int t = array[a];
        array[a] = array[b];
        array[b] = t;
    }

    public void reverse(int[] array, int start, int end) {
        if (array == null || array.length <= 1) {
            return;
        }
        for (int i = start, j = end; i < j; i++, j--) {
            swap(array, i, j);
        }
    }

    public void rotate(int[] nums, int k) {
        if (k == 0) {
            return;
        }
        int n = nums.length;
        if (k > n) {
            k = k % n;
        }
        reverse(nums, 0, n - 1 - k);
        reverse(nums, n - k, n - 1);
        reverse(nums, 0, n - 1);
    }
}

python¶

# -*- coding: utf-8 -*-

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        if k == 0:
            return
        n = len(nums)
        if k > n:
            k = k % n

        self.reverse(nums, 0, n - 1 - k)
        self.reverse(nums, n - k, n - 1)
        self.reverse(nums, 0, n - 1)

    def swap(self, array, a, b):
        t = array[a]
        array[a] = array[b]
        array[b] = t

    def reverse(self, array, start, end):
        if array is None or len(array) <= 1:
            return
        i, j = start, end
        while i < j:
            self.swap(array, i, j)
            i, j = i + 1, j - 1


if __name__ == "__main__":
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    solution = Solution()
    print nums
    solution.rotate(nums, 4)
    print nums

Related Posts

  • LeetCode [1] Two Sum
  • LeetCode [2] Add Two Numbers
  • LeetCode [58] Length of Last Word
  • LeetCode [190] Reverse Bits
  • LeetCode [151] Reverse Words in a String

  • « LeetCode [2] Add Two Numbers
  • LeetCode [7] Reverse Integer »

Published

8月 20, 2016

Last Updated

8月 20, 2016

Category

Linux

Tags

  • LeetCode 13

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor