[LeetCode]5. Move Zeros移动0到数组末尾
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
解法:注意非零元素移到数组前面后的顺序与原来的相对顺序不能改变,并且不能另外开辟临时数组。思路:(1)设置两个游标:index1=0, index2=0;(2)从头往后扫描,若当前元素非零,则index1++,直至找到数组中第一个零元素;(3)设置index2=index1+1,从此处继续往后扫描,若当前元素为0,则index2++,直至找到第一个零元素后的第一个非零元素;(4)交换这两个元素swap(arr[index1], arr[index2]);(5)index1++,重复步骤(2)(3)(4),直至index1或者index2超出数组长度。时间复杂度O(n)。
class Solution { public: void moveZeroes(vector<int>& nums) { int n = nums.size(); if(n < 2) return; int ind1 = 0; int ind2 = 0; while (ind1 < n && ind2 < n) { while (ind1 < n && nums[ind1] != 0) ind1++; ind2 = ind1 + 1; while (ind2 < n && nums[ind2] == 0) ind2++; if (ind1 >= n || ind2 >= n) break; swap(nums[ind1], nums[ind2]); ind1++; } } private: void swap(int& a, int&b) { a = a + b; b = a - b; a = a - b; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步