首页 > 其他 > 详细

LeetCode_283

时间:2019-03-09 17:27:48      阅读:163      评论:0      收藏:0      [点我收藏+]

题目描述:

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.

实现思路:

定义区间 [0,k) 为非零元素,遍历nums,当元素不为0时将其与nums[k]互换,[k,n)内剩余的元素自然就是0

代码如下:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int k =0;
        for(int i = 0; i < nums.size(); ++i)
            if(nums[i])
                swap(nums[k++], nums[i]);
    }
};

 

LeetCode_283

原文:https://www.cnblogs.com/harchar/p/10501976.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!