本文主要是介绍LeetCode 题解(214) : Move Zeroes,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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.
三个指针,zero指向最前零的位置,start指向zero后第一个不为0的位置,end指向start之后下一个零之前最后一个不为零的位置。递增三指针。
C++版:
class Solution {
public:void moveZeroes(vector<int>& nums) {int zero = 0, start = 0, end = 0;while(true) {while(nums[zero] != 0 && zero < nums.size())zero++;if(zero == nums.size())break;start = zero + 1;while(nums[start] == 0 && start < nums.size())start++;if(start == nums.size())break;end = start;while(nums[end] != 0 && end < nums.size())end++;end--;for(int i = start; i <= end; i++) {nums[zero] = nums[i];zero++;}for(int i = zero; i <= end; i++) {nums[i] = 0;} }}
};
Java版:
public class Solution {public void moveZeroes(int[] nums) {int zero = 0, start = 0, end = 0;while(true) {while(zero < nums.length && nums[zero] != 0)zero++;if(zero == nums.length)return;start = zero + 1;while(start < nums.length && nums[start] == 0)start++;if(start == nums.length)return;end = start;while(end < nums.length && nums[end] != 0)end++;end--;for(int i = start; i <= end; i++) {nums[zero] = nums[i];zero++;}for(int i = zero; i <= end; i++)nums[i] = 0;}}
}
Python版:
class Solution(object):def moveZeroes(self, nums):""":type nums: List[int]:rtype: void Do not return anything, modify nums in-place instead."""zero, start, end = 0, 0, 0while True:while zero < len(nums) and nums[zero] != 0:zero += 1if zero == len(nums):returnstart = zero + 1while start < len(nums) and nums[start] == 0:start += 1if start == len(nums):returnend = startwhile end < len(nums) and nums[end] != 0:end += 1end -= 1for i in range(start, end + 1):nums[zero] = nums[i]zero += 1for i in range(zero, end + 1):nums[i] = 0
这篇关于LeetCode 题解(214) : Move Zeroes的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!