Given an integer array nums
, move all 0
‘s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2:
Input: nums = [0] Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
class Solution {
public:
void moveZeroes(vector& nums) {
int i=0,j=0;
while(j
The purpose of this function is to move all the zeroes to the end of the list while keeping the numbers in the same order.
Let’s see the approach to this problem:
Initialise two variables, ‘i’ and ‘j’, both set to 0. These variables are used to iterate through the vector.
Inside the loop, we check
And our result will be obtained.
It’s like organizing a line of numbers. The non-zero numbers go to the front, and all the zeros naturally end up at the back.
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India