Header Ad

Leetcode Rotate Array problem solution

In this Leetcode Rotate Array problem solution, You are Given an array, rotate the array to the right by k steps, where k is non-negative.

Leetcode Rotate Array problem solution


Problem solution in Python.

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in range(k):
            lastValue = nums[len(nums)-1]
            firstValue = nums[0]
            del(nums[len(nums)-1])
            nums.insert(0, lastValue)



Problem solution in Java.

public void rotate(int[] nums, int k) {
        int n = nums == null ? 0 : nums.length;
        if (n == 0)
            return;
        int offset = k%n;
        int j = offset > 0 ? offset - 1 : n + offset - 1;
        reverse(nums, 0, n - 1);
        reverse(nums, 0, j);
        reverse(nums, j + 1, n - 1);
    }
    
    private void reverse(int[] nums, int start, int end){
        while(start < end){
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] = tmp;
            ++start;
            --end;
        }
    }


Problem solution in C++.

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int len = nums.size();
        int d = gcd(len, k=k%len);
        int pos, next_pos;
        int tmp, tmp_next;

        for (int i = 0; i < d; ++i) {
            pos = i;
            tmp = nums[pos];
            do {
                next_pos = (pos+k) % len;
                tmp_next = nums[next_pos];
                nums[next_pos] = tmp;

                pos = next_pos;
                tmp = tmp_next;
            } while (pos != i);
        }
    }

    int gcd(int a, int b)
    {
        int t;

        while (b != 0) {
            t = a%b;
            a = b;
            b = t;
        }
        return a;
    }
};


Problem solution in C.

void rotate(int* nums, int numsSize, int k) {
    if( numsSize < 2 || ( k % numsSize == 0 ) ) return;    
    for( ;k>numsSize; ) k = k % numsSize;
    int* temp1 = (int*)malloc(sizeof(int)*k);
    int* temp2 = (int*)malloc(sizeof(int)*(numsSize-k));
    int count = 0;// counter
    for(int i=(numsSize-k); count!=k; i++){ // afterwards
        temp1[count] = nums[i];
        count++;
    }
    for(int i=0; i<(numsSize-k); i++) temp2[i] = nums[i]; // forwards
    for(int i=0; i<k; i++) nums[i] = temp1[i]; // forwards
    for(int i=k; i<numsSize; i++) nums[i] = temp2[i-k]; // afterwards
}


Post a Comment

0 Comments