• 数组//移动零


    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

    示例:

    输入: [0,1,0,3,12]
    输出: [1,3,12,0,0]

    说明:

    1. 必须在原数组上操作,不能拷贝额外的数组。
    2. 尽量减少操作次数。
    class Solution {
        public void moveZeroes(int[] nums) {
            int curIndex = nums.length-1;
            int lastIndex = nums.length-1;
            int count = 0;
            while(curIndex >= 0){
                if(nums[curIndex] == 0){
                    count = lastIndex - curIndex;
                    for(int i = 0; i < count; i++){
                        nums[curIndex+i] = nums[curIndex+i+1];
                    }
                    nums[lastIndex] = 0;
                    lastIndex--;
                }
                curIndex--;
            }
        }
    }
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int curIndex=nums.size()-1;
            int lastIndex = nums.size()-1;
            int count=0;
            while(curIndex>=0){
                if(nums[curIndex] == 0){
                    count = lastIndex-curIndex;
                    for(int i=0;i<count;i++){
                        nums[curIndex+i] = nums[curIndex+i+1];
                    }
                    nums[lastIndex] = 0;
                    lastIndex--;
                }
                curIndex--;
            }
        }
    };

    最好的方法:

    class Solution {
        public void moveZeroes(int[] nums) {
            if(nums == null || nums.length == 0){
                return;
            }
            //记录非o元素开始位置
            int k = 0;
            for(int i=0;i<nums.length;i++){
                if(nums[i] != 0) {
                    nums[k++] = nums[i];
                }
            }
            while(k < nums.length) {
                nums[k] = 0;
                k++;
            }
        }
    }
  • 相关阅读:
    超全面的vue.js使用总结
    Python3 [字典】类型 学习笔记
    Python3 [集合]类型 学习笔记
    Python 希尔排序法
    Python 堆排序法
    Python 归并排序法
    Python 冒泡排序法
    Python 选择排序法
    Python 快速排序法(转)
    Python 插入排序法
  • 原文地址:https://www.cnblogs.com/strawqqhat/p/10602418.html
Copyright © 2020-2023  润新知