#Leetcode# 283. Move Zeroes

https://leetcode.com/problems/move-zeroes/

 

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.

Example:

Input: [0,1,0,3,12]
Output: [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.

代码:

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

  很纠结晚上要不要粗去走一走今天天气还不错

 

posted @ 2019-01-19 15:48  丧心病狂工科女  阅读(106)  评论(0编辑  收藏  举报