Skip to content

Conversation

@mmudimba
Copy link

@mmudimba mmudimba commented Dec 9, 2021

This is LeetCode solution to the "189.) Rotate Array" problem. Enjoy!

return nums;

}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The alternative solution

class Solution {
    private void reverse(int[] nums, int l, int r) {
        while (l <= r) {
            int temp = nums[l];
            nums[l] = nums[r];
            nums[r] = temp;
            l++;
            r--;
        }
    }

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both solution are correct

Copy link

@Tanmaybhujade Tanmaybhujade left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

solution are correct

return nums;

}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both solution are correct

@Tanmaybhujade
Copy link

one more alternate solution.

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

private void reverse(int[] nums, int start, int end) {
    while(start < end) {
        nums[start] = nums[start] ^ nums[end];
        nums[end] = nums[start] ^ nums[end];
        nums[start] = nums[start] ^ nums[end];
        start++;
        end--;
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants