zoukankan      html  css  js  c++  java
  • lintcode:移动零

    题目

    给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

     注意事项

    1.必须在原数组上操作
    2.最小化操作数

    样例

    给出 nums = [0, 1, 0, 3, 12], 调用函数之后, nums = [1, 3, 12, 0, 0].

    解题

    快速排序思想,以0为界划分

    public class Solution {
        /**
         * @param nums an integer array
         * @return nothing, do this in-place
         */
        public void moveZeroes(int[] nums) {
            // Write your code here
            int slow = -1;
            int fast = 0;
            int n = nums.length;
            int x = 0;
            while(slow < fast && fast < n){
                if(nums[fast]!=x){
                    slow++;
                    swap(nums,slow,fast);
                }
                fast++;
            }
        }
        public void swap(int[] A,int i,int j){
            int tmp = A[i];
            A[i] = A[j];
            A[j] = tmp;
        }
    }

    稍作更新

    public class Solution {
        /**
         * @param nums an integer array
         * @return nothing, do this in-place
         */
        public void moveZeroes(int[] nums) {
            // Write your code here
            int one = 0;
            int fast = 0;
            int n = nums.length;
            int x = 0;
            for(int i=0;i<n;i++){
                if(nums[i]!=x) { // 不为0 的向前移动
                    nums[one] = nums[i];
                    one++;
                }
            }
            for(int i= one;i<n;i++) // 后面的就是0
                nums[i] = x;
        }
    
    }
  • 相关阅读:
    回味Python2.7——笔记3
    回味Python2.7——笔记2
    tensorflow softmax_cross_entropy_with_logits函数
    tensorflow l2_loss函数
    tensorflow l2_normalize函数
    tensorflow bias_add应用
    Hadoop Shell命令
    在Linux上安装ant环境
    调整虚拟机中Linux的分辨率
    安装virtualBox 增强包
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5649098.html
Copyright © 2011-2022 走看看