MDGSF Software Engineer

[算法学习][leetcode] 283. 移动零

2020-03-07
mdgsf
Art

https://leetcode-cn.com/problems/move-zeroes/

参考答案

Python 代码

class Solution:
  def moveZeroes(self, nums: List[int]) -> None:
    """
    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

JavaScript 代码

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
  let j = 0;
  for (let i = 0; i < nums.length; i += 1) {
    if (nums[i] !== 0) {
      [nums[i], nums[j]] = [nums[j], nums[i]];
      j += 1;
    }
  }
};

Rust 代码

impl Solution {
  pub fn move_zeroes(nums: &mut Vec<i32>) {
    let mut j = 0;
    for i in 0..nums.len() {
      if nums[i] != 0 {
        if j != i {
          nums.swap(i, j);
        }
        j += 1;
      }
    }
  }
}

Golang 代码

func moveZeroes(nums []int) {
	j := 0
	for i := range nums {
		if nums[i] != 0 {
			nums[i], nums[j] = nums[j], nums[i]
			j++
		}
	}
}

C++ 代码

class Solution {
public:
  void moveZeroes(vector<int>& nums) {
    int j = 0;
    int n = nums.size();
    for (int i = 0; i < n; i++) {
      if (nums[i] != 0) {
        swap(nums[i], nums[j++]);
      }
    }
  }
};

weixingongzhonghao

Similar Posts

Comments