zoukankan      html  css  js  c++  java
  • 283. 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:

    1. You must do this in-place without making a copy of the array.
    2. Minimize the total number of operations.

    链接: http://leetcode.com/problems/move-zeroes/

    3/7/2017

     1 public class Solution {
     2     public void moveZeroes(int[] nums) {
     3         if (nums.length == 0) return;
     4         int i = 0, j = 0, count = 0;
     5         while (j < nums.length) {
     6             if (nums[j] == 0) {
     7                 j++;
     8                 count++;
     9                 continue;
    10             }
    11             if (count > 0) nums[i] = nums[j];
    12             i++;
    13             j++;
    14         }
    15         while (i < nums.length) {
    16             nums[i++] = 0;
    17         }        
    18     }
    19 }

    别人的算法更加简洁,大致上是一样的。

    4/16/2017

    BB电面准备

     1 public class Solution {
     2     public void moveZeroes(int[] nums) {
     3         if (nums == null || nums.length == 0) return; 
     4         int i = 0;
     5         for (int j = 0; j < nums.length; j++) {
     6             if (nums[j] == 0) continue;
     7             else {
     8                 if (i == j) {
     9                     i++; 
    10                     continue;
    11                 }
    12                 nums[i++] = nums[j];
    13             }
    14         }
    15         while (i < nums.length) nums[i++] = 0;
    16         return;
    17     }
    18 }
  • 相关阅读:
    BNU Online Judge-29140
    HDU-1022-Train Problem I
    HDU-1312-Red and Black
    BNU Online Judge-34978-汉诺塔
    BNU Online Judge-34976-数细菌
    BNU Online Judge-34973-Liserious战队
    HDU-1010-Tempter of the Bone
    HDU-1518-Square
    thinkphp笔记
    1210. 连号区间数
  • 原文地址:https://www.cnblogs.com/panini/p/6517643.html
Copyright © 2011-2022 走看看