Leetcode 283 MoveZeros

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array
  2. Minimize the total number of operations.

Solution:
算法一:最基础最简单的能想到的算法便是直接将零一个一个地往后挪,但这种算法效率比较低,时间复杂度为O(n^2)

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for(int i=0; i<nums.size(); i++){
        	if(nums[i] == 0){
        		for(int j=i+1; j<nums.size(); j++){
        			if(nums[j] != 0){
        				nums[i] = nums[j];
        				nums[j] = 0;
        				break;
        			} 
        		}
        	}
        }
    }
};

算法二:很惊艳的算法,直接将非0的数往前挪,最后以0补空位(从别人的博客所看到的),时间复杂度为O(n)

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


点赞