I am completing the CodingBat exercises for Java, and, having learnt from the answers to the previous one, I completed the one that follows:
Return a version of the given array where all the
10
s have been removed. The remaining elements should shift left towards the start of the array as needed, and the empty spaces a the end of the array should be0
. So{1, 10, 10, 2}
yields{1, 2, 0, 0}
. You may modify and return the given array or make a new array.
Here is my code:
public int[] withoutTen(int[] nums) {
int slow = 0;
for (int fast = 0; fast < nums.length; fast++) {
if (nums[fast] != 10) {
nums[slow] = nums[fast];
slow++;
}
if (fast == nums.length-1) {
for (int i = fast; i >= slow; i--) {
nums[i] = 0;
}
}
}
return nums;
}
Please bear in mind I am doing these without importing anything extra like java.util.Arrays
etc., as, primarily, this is not accepted by the assessor and, secondarily, I want to get to grips with arrays without importing anything extra yet.
I was taking influence from the comments I received on the previous question, by using a fast
and slow
variable for looping through the array, and limiting the code to one main for
loop, for the sake of making my code generally better and putting efficiency into practice.
How could this be optimised? Is it ok to begin another loop only for the circumstance of fast
reaching the last element in the array? It feels like I am repeating myself by saying "if we get to the last element..." because we absolutely will do anyway.
I played around with setting fast
outside the loops, so that the second for
loop can begin after the first (as opposed to nesting it). At that point, fast
would be set to the last value anyway from having completed the previous loop, but more and more values would be set outside the loops. Which way makes more sense?