LeetCode 283 Move Zeroes(移動全部的零元素)

來源:互聯網
上載者:User

標籤:each   esc   key   lis   ini   lin   text   using   array   

翻譯
給定一個數字數組。寫一個方法將全部的“0”移動到數組尾部。同一時候保持其餘非零元素的相對位置不變。比如,給定nums = [0, 1, 0, 3, 12],在調用你的函數之後,nums應該變為[1, 3, 12, 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.For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].Note:You must do this in-place without making a copy of the array.Minimize the total number of operations.
分析

一開始我還以為是要給非零元素排序呢,後來細緻一看僅僅是保持相對位置不變就好了。

那就easy非常多了呀。

0 1 0 3 12 (index = 0, current = 0)1 0 0 3 12 (index = 1, current = 1)1 0 0 3 12 (index = 1, current = 2)1 3 0 0 12 (index = 2, current = 3)1 3 12 0 0 (index = 3, current = 4)

按上面的步驟來,當前的數字是0的話不做操作。非零的話將其與第一個零互換位置。

其核心在於這個第一個零的位置是怎樣變化的。即便一開始不是0也沒關係,大不了讓這個非零數和自己交換位置唄,比方說:

1 2 0 3 12 (index = 0, current = 0)1 2 0 3 12 (index = 1, current = 1)1 2 0 3 12 (index = 2, current = 2)1 2 3 0 12 (index = 3, current = 3)1 2 3 12 0 (index = 4, current = 4)

翻譯成代碼就是:

#include <iostream>#include <vector>using namespace std;void moveZeroes(vector<int>& nums) {    for (int index = 0, current = 0; current < nums.size(); current++) {        if (nums[current] != 0)            swap(nums[index++], nums[current]);    }}int main() {    vector<int> v;    v.push_back(1);    v.push_back(2);    v.push_back(0);    v.push_back(3);    v.push_back(12);    moveZeroes(v);    for (auto i : v) {        cout << i << " ";    }    return 0;}
代碼
class Solution {public:    void moveZeroes(vector<int>& nums) {        for (int index = 0, current = 0; current < nums.size(); current++) {            if (nums[current] != 0)                swap(nums[index++], nums[current]);        }    }};

LeetCode 283 Move Zeroes(移動全部的零元素)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.