Skip to content

283. Move Zeroes #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
w4irdo opened this issue Jul 25, 2019 · 1 comment
Open

283. Move Zeroes #8

w4irdo opened this issue Jul 25, 2019 · 1 comment

Comments

@w4irdo
Copy link
Owner

w4irdo commented Jul 25, 2019

# 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.

# Python 1

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        type nums: List[int]
        Do not return anything, modify nums in-place instead.
        """
        count = nums.count(0)
        nums[:] = [i for i in nums if i != 0]
        nums += [0] * count

# Python 2

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        type nums: List[int]
        Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1
  • nums[:] 属于浅拷贝。列表内的元素内存地址并未发生改变。
@w4irdo
Copy link
Owner Author

w4irdo commented Jul 25, 2019

# Java
class Solution {
    public void moveZeroes(int[] nums) {
        int j = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] != 0) {
                int temp = nums[j];
                nums[j] = nums[i];
                nums[i] = temp;
                j++;
            }
        }
    }
}
  • Java 的方法和楼上的 Python 第二种方法相同。先判断元素不为零,则交换元素。Java 版运行时间 0
    ms,但空间上花费要比 Python 多。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant