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.
1 Answer 1
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....
-
1\$\begingroup\$ I'd omit the
nums == null
check. Your method is null-safe, but most Java methods are not, which means that the programmer must handle nulls somewhere. If they don't, they'll get an NPE and the sooner the better. \$\endgroup\$maaartinus– maaartinus2015年04月06日 23:04:57 +00:00Commented Apr 6, 2015 at 23:04 -
\$\begingroup\$ @rolfl
What if we want to shift it to right?
\$\endgroup\$paul– paul2015年11月30日 05:16:14 +00:00Commented Nov 30, 2015 at 5:16 -
\$\begingroup\$ @paul - then adjust the indices you see in the code to be in the other direction.... so, for example instead of
int start = nums[0]
haveint start = nums[nums.length - 1]
\$\endgroup\$rolfl– rolfl2015年11月30日 05:26:19 +00:00Commented Nov 30, 2015 at 5:26 -
\$\begingroup\$ what if we want to shift it 50 times to the left but array length is 20!? your solution would have a bug then I'd say. \$\endgroup\$Mona Jalal– Mona Jalal2016年05月01日 07:17:14 +00:00Commented May 1, 2016 at 7:17
-
2\$\begingroup\$ @MonaJalal - well, no.... it has no bug. Your comment makes no sense. The original question is to only shift by 1, and there is not even an argument/parameter to specify any other shift distance. The only way to shift by 50 is to call the method 50 times, and it will work just fine then \$\endgroup\$rolfl– rolfl2016年05月01日 11:51:22 +00:00Commented May 1, 2016 at 11:51
Explore related questions
See similar questions with these tags.