• 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;
        }
    
    }
  • 相关阅读:
    go2基本类型
    go1
    android studio 使用
    ios34---GDC,dispatch_once
    ios33--线程通信
    ios33--线程安全
    ios32---线程的状态
    ios31--NSThread
    ios30---pthread, NSThread, GCD, NSOperation
    ios29--多线程
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5649098.html
Copyright © 2020-2023  润新知