Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create RotateArray.java #149

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions Java/RotateArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/******************************************************************************
189.) Rotate Array
Difficulty: Medium
Description: Given an array, rotate the array to the right by k steps, where k is non-negative.

Naive Approach: Create a function that rotates the array onces, then rotate the array k times.
Efficient Approach: Reverse the whole list, then reverse the first k elements, and the last n - k elements.
*******************************************************************************/

public class RotateArray
{
public static void main(String[] args) {

/* This is the test, expected output is [4,5,1,2,3] */

int [] arr = {1,2,3,4,5};

rotate(arr, 2);

int[] rotate_arr = arr;

for(int i = 0; i < rotate_arr.length; i++){
System.out.print(rotate_arr[i] + " ");
}

}

public static void rotate(int[] nums, int k) {
k = k % nums.length;


reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k-1);
reverse(nums, k, nums.length - 1);
}

public static int [] reverse(int [] nums, int start, int end){
int indx_end = end, indx_start = start;

while(indx_start < indx_end){
int temp = nums[indx_start];
nums[indx_start] = nums[indx_end];
nums[indx_end] = temp;
indx_start++;
indx_end--;

}

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