HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Left Shifting an array of ints

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayleftshiftingints

Problem

The problem I am referring to is here

So basically it's about shifting an array of ints 1 position to the left and relocating the lost first int in the start of the array to the last position at the right:

\$\mathrm{shiftLeft}(\{6, 2, 5, 3\}) → \{2, 5, 3, 6\}\$

\$\mathrm{shiftLeft}(\{1, 2\}) → \{2, 1\}\$

\$\mathrm{shiftLeft}(\{1\}) → \{1\}\$

Please feel free to review the code below:

public int[] shiftLeft(int[] nums) {
    for(int i = 0, start = 0; i < nums.length; i++)
    {
        if(i == 0)
            start = nums[i];
        if(i == (nums.length -1))
        {
            nums[i] = start;
            break;
        }    
        nums[i] = nums[i + 1];
    }
    return nums;            
}


Also I would like to get rid of the variable start and try to solve it only using the loop iterator i, any suggestions are welcome.

Solution

Your current solution is actually pretty good, conceptually. There's nothing wrong with the start variable. I am not sure why you want to remove it. The loop is logically a good solution, but there's a better way than that, though (better because you can make the system do it for you....).

public int[] shiftLeft(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return nums;
    }
    int start = nums[0];
    System.arraycopy(nums, 1, nums, 0, nums.length - 1);
    nums[nums.length - 1] = start;
    return nums;
}


Note that, in addition to using System.arraycopy I also check to see that the input has valid values available....

Code Snippets

public int[] shiftLeft(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return nums;
    }
    int start = nums[0];
    System.arraycopy(nums, 1, nums, 0, nums.length - 1);
    nums[nums.length - 1] = start;
    return nums;
}

Context

StackExchange Code Review Q#86016, answer score: 9

Revisions (0)

No revisions yet.