当前位置:首页 > 移动开发 > 正文

LeetCode 283. 移动零

2024-03-31 移动开发

题目链接:https://leetcode-cn.com/problems/move-zeroes/

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

思路:把非零元素前移最后补零就行了

 1 void moveZeroes(int* nums, int numsSize){
 2     int t=0;
 3     for(int i=0;i<numsSize;i  ){
 4         if(nums[i]!=0){
 5             nums[t  ]=nums[i];
 6         }
 7     }
 8     for(int i=t;i<numsSize;i  ){
 9         nums[i]=0;
10     }
11 }

 

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/yidong/18561.html