Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- Example:
- --------
- Input: [0,1,0,3,12]
- Output: [1,3,12,0,0]
- Note:
- -----
- 1. You must do this in-place without making a copy of the array.
- 2. Minimize the total number of operations.
- */
- namespace Problems.LeetCode.Array.MoveZeroes_283
- {
- public class Solution
- {
- /// <summary>
- /// Moves all zeros to the end of an array.
- /// Moves non zeros to the left first then fills the rest with zeros.
- /// Time complexity : O(n)
- /// Space complexity : O(1)
- /// </summary>
- /// <param name="nums">An array of integers.</param>
- public void MoveZeroes(int[] nums)
- {
- var insertAt = 0;
- for (var i = 0; i < nums.Length; i++)
- if (nums[i] != 0)
- nums[insertAt++] = nums[i];
- while (insertAt < nums.Length)
- nums[insertAt++] = 0;
- }
- /// <summary>
- /// Moves all zeros to the end of an array.
- /// Uses two pointers and swapping.
- /// Time complexity : O(n)
- /// Space complexity : O(1)
- /// </summary>
- /// <param name="nums">An array of integers.</param>
- public void MoveZeroes2(int[] nums)
- {
- var insertAt = 0;
- for (var i = 0; i < nums.Length; i++)
- {
- if (nums[i] != 0)
- {
- var temp = nums[insertAt];
- nums[insertAt++] = nums[i];
- nums[i] = temp;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement