LeetCode //C - 283. Move Zeroes

发布时间:2023年12月20日

283. Move Zeroes

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 < = n u m s . l e n g t h < = 1 0 4 1 <= nums.length <= 10^4 1<=nums.length<=104
  • ? 2 31 < = n u m s [ i ] < = 2 31 ? 1 -2^{31} <= nums[i] <= 2^{31} - 1 ?231<=nums[i]<=231?1

From: LeetCode
Link: 283. Move Zeroes


Solution:

Ideas:
  • We iterate through the array with a for loop.
  • If an element is not zero, we move it to the insertPos index and increment insertPos.
  • After all non-zero elements are moved to the front, we fill the rest of the array with zeros, starting from insertPos to the end of the array.
Code:
void moveZeroes(int* nums, int numsSize) {
    int insertPos = 0;  // This will keep track of the position where we need to insert the next non-zero element.
    for (int i = 0; i < numsSize; i++) {
        if (nums[i] != 0) {
            nums[insertPos++] = nums[i];  // Move non-zero elements to the front and increment insertPos.
        }
    }
    while (insertPos < numsSize) {
        nums[insertPos++] = 0;  // Fill the remaining array with zeroes.
    }
}
文章来源:https://blog.csdn.net/navicheung/article/details/135075670
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。