美文网首页
LeetCode 第283题: 移动零

LeetCode 第283题: 移动零

作者: 放开那个BUG | 来源:发表于2021-06-09 00:09 被阅读0次

    1、前言

    题目描述

    2、思路

    这里使用快速排序的思路,只不过快排有 less、more 两个区间,这边只要 less 即可,将大于0或者小于0的数都移到 less 那边。

    3、代码

    class Solution {
        public void moveZeroes(int[] nums) {
            if(nums == null || nums.length == 0){
                return;
            }
    
            int less = -1, L = 0;
            while(L < nums.length){
                if(nums[L] < 0 || nums[L] > 0){
                    swap(nums, L++, ++less);
                }else {
                    L++;
                }
            }
        }
    
        private void swap(int[] nums, int i, int j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode 第283题: 移动零

          本文链接:https://www.haomeiwen.com/subject/vypwjltx.html