LeetCode 283. Move Zeroes

来源:互联网 发布:关于养生之道的软件 编辑:程序博客网 时间:2024/06/07 01:23

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.
题目意思:就是给你一个数组,然后把所有的0交换到数组最后,并且最后的非零数字递增的,要求交换次数最少
题解:
本人的解法:开辟一个指针指向当前数组的元素,在开辟一个指针指向后一个元素,然后对后一个元素进行遍历,若为非0值,则跟第一个指针指向的0元素交换,更新指针指向,直到所有0交换到最后,以下是我的代码
void moveZeroes(vector<int>& nums) {        int len = nums.size();                for (int i = 0; i < len; i++){            int left = i+1;            while(left < len){                if (nums[i] == 0 && nums[left] != 0){                    swap(nums[i],nums[left]);                }                left++;            }        }            }

下面是看了别人的代码写的,时间复杂度低
void moveZeroes(vector<int>& nums) {        int len = nums.size();        int left = 0,right = 0;        while (right < len){            if (nums[right] != 0){                swap(nums[left],nums[right]);                left++;            }            right++;        }