In my code, I get an output of an array but it displays some unwanted zeros after getting the array, Can you explain a way to avoid getting these unwanted zeros.
static int[] cutTheSticks(int[] arr) {
int min,i,j,count=0;
int []arr2=Arrays.copyOf(arr,arr.length);
int []temp =Arrays.copyOf(arr,arr.length);
for(i=0;i<arr.length;i++){
Arrays.sort(arr2);
min= arr2[0];
for(j=0;j<arr.length;j++){
if(temp[j]>0){
count++;
}
temp[j]=temp[j]-min;
}
int []res = new int [arr.length];
while(count!=0) {
res[i] = count;
count = 0;
}
return res;
}
You can figure the "size" of res
without its trailing zeros with:
int rlen = res.length;
while (res[rlen-1] == 0) {
--rlen;
}
If you wish, you can then use the calculated "effective length" rlen
to reallocate the res
array at the correct size:
res = Arrays.copyOf(res, rlen);
Or just use rlen
instead of res.length
when you need to know the "correct" size of res
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.