刷题283. Move Zeroes

一、题目说明

题目283. Move Zeroes,给定一组数,将该组数中的0移动末尾,其他数据相对位置不变。

二、我的解答

class Solution{
	public:
		void moveZeroes(vector<int>& nums){
			if(nums.size()<2){
				return;
			}
			int len = nums.size();

			int i=0,j=0;
			//i指向更新的位置,j指向非0元素
			while(i<len &&j<len){
				if(nums[j]==0){
					j++; 
				}else{
					nums[i] = nums[j];
					i++;
					j++;
				}
			}
			for(int t = i;t<len;t++){
				nums[t] = 0;
			}
		}
};

性能如下:

Runtime: 12 ms, faster than 97.09% of C++ online submissions for Move Zeroes.
Memory Usage: 9.5 MB, less than 87.50% of C++ online submissions for Move Zeroes.

三、优化措施

从左到右遍历数组,统计0的个数,num[i]为整数,则将其移动到nums[i-count]

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

性能

Runtime: 12 ms, faster than 97.09% of C++ online submissions for Move Zeroes.
Memory Usage: 9.5 MB, less than 84.72% of C++ online submissions for Move Zeroes.
posted @ 2020-04-11 07:57  siwei718  阅读(87)  评论(0编辑  收藏  举报