题目:
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.
思路:可以该数组从后向前遍历,遇到0就把0放至末尾;或者从前遍历遇到非0元素则依次放在数组前,最后将后边元素全部置为0
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCode { class MoveZerosSolution { public void MoveZeroes(int[] nums) { //O(n2) for (int i = nums.Length - 1; i >= 0; i--) { if (nums[i] == 0) { for (int j = i; j < nums.Length - 1; j++) { nums[j] = nums[j + 1]; } nums[nums.Length - 1] = 0; } } /*O(1)解法 int index = 0; for(int i = 0;i < nums.Length;i++) if(nums[i] != 0) { nums[index] = nums[i]; index++; } for(int j = index;j < nums.Length;j++) nums[j] = 0; */ } } }
本文介绍了一种算法,用于将数组中的所有零元素移动到数组的末尾,同时保持非零元素的相对顺序。提供了两种解决方案,一种是通过遍历数组并将零元素后移,另一种是在遍历过程中将非零元素前移,最后填充剩余位置为零。讨论了操作数和空间复杂度,并附带了C#代码实现。
153

被折叠的 条评论
为什么被折叠?



