swap(nums, left, right);
Syntax:
public static void swap(List list, int i, int j)
Parameters: This method takes the following argument as a Parameter
list – The list in which to swap elements.
i – the index of one element to be swapped.
j – the index of the other element to be swapped.
java-solution
class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length;
int left = 0;
int right = 0;
while (right < n){
//如果右指针不是0,左右指针互换,然后左指针+1,继续比较
if(nums[right] != 0){
//将nums中index为left和index为right的值互换
swap(nums, left, right);
//然后左指针往右移动,保持左指针左侧是非零
left++;
}
//如果nums[right] == 0;则左指针不动,右指针向右
//保证左指针到右指针之间是0
right++;
}
}
public void swap(int[] nums, int left, int right){
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
复杂度分析
时间复杂度:O(n),其中 n为序列长度。每个位置至多被遍历两次。
空间复杂度:O(1)。只需要常数的空间存放若干变量。
python solution
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0 and nums[slow] == 0:
nums[slow], nums[fast] = nums[fast], nums[slow]
if nums[slow] != 0:
slow += 1