The given solution is an implementation of the moveZeroes function that moves all the zeroes in the input vector to the end while maintaining the order of the non-zero elements.

The function takes a vector of integers (nums) as input and returns void.

First, it initializes three variables: n (the size of the input vector), left (the index to place the next non-zero element), and right (the current index being checked).

Then, it enters a while loop that continues until the right index reaches the end of the vector.

Inside the loop, it checks if the current element at the right index is non-zero (nums[right] != 0). If it is non-zero, it swaps the element at the left index with the element at the right index, and increments the left index by 1. This effectively moves the non-zero element to the left side of the vector.

After the swap and increment, it increments the right index by 1 to move on to the next element.

Once the loop finishes, all the non-zero elements will be moved to the left side of the vector, while the zeroes will remain at the end in their original order.


原文地址: http://www.cveoy.top/t/topic/pkvw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录