I read such a solution to rotate an array
the question:
public class Solution {
public void rotate(int[] nums, int k) {
int temp, previous;
for (int i = 0; i < k; i++) {
previous = nums[nums.length - 1];
for (int j = 0; j < nums.length; j++) {
temp = nums[j];
nums[j] = previous;
previous = temp;
}
}
}
}
I am confused about previous = nums[num.lengh -1]
,
is it a range as nums[0:10]
or a single element as nums[0]
?
It is a single element, because num.lengh - 1
is an int
and just gives you the last accessible index of the array.
If you check wether the length of the array is > 0
, then you can safely use the length of the array to determine the last accessible index.
The length of an array is very often used in loops like yours:
Here the length is used to make sure you don't access unavailable indexes:
for (int j = 0; j < nums.length; j++)
You can write slightly a different condition without changing the functionality
for (int j = 0; j <= nums.length - 1; j++)
But if you do the following, you will get an IndexOutOfBoundsException
:
for (int j = 0; j <= nums.length; j++)
The last iteration would try to access nums[nums.length], which isn't there...