LeetCode移动零
LeetCode移动零
给定一个数组 nums ,编写一个函数将所有 0 移动到数组的末尾 ,同时保持非零元素的相对顺序。
说明:
- 必须在原数组上操作 ,不能拷贝额外的数组 。
- 尽量减少操作次数。
void moveZeroes(int* nums, int numsSize){ int count = 0, length = numsSize-1; while (length >= 0) { if(nums[length] == 0) { count++;//计数 int temp = length; while (temp < numsSize-1) { nums[temp] = nums[temp+1]; temp++; } } length--; } while (count >0) { nums[numsSize-count] = 0; count--; }}官方答案 :双指针法
思路及解法
使用双指针 ,左指针指向当前已经处理好的序列的尾部,右指针指向待处理序列的头部。
右指针不断向右移动,每次右指针指向非零数 ,则将左右指针对应的数交换,同时左指针右移。
注意到以下性质:
左指针左边均为非零数;
右指针左边直到左指针处均为零。
因此每次交换 ,都是将左指针的零与右指针的非零数交换,且非零数的相对顺序并未改变。
void swap(int *a, int *b) { int t = *a; *a = *b, *b = t;}void moveZeroes(int *nums, int numsSize) { int left = 0, right = 0; while (right < numsSize) { if (nums[right]) { swap(nums + left, nums + right); left++; } right++; }}展开阅读全文投稿时间:2022-01-24 最后更新 :2022-09-09
标签:气流干燥设备