LintCode之移動零

來源:互聯網
上載者:User

標籤:move   lint   int   9.png   題目   .com   一個   als   元素   

題目描述:

 

分析:由於要使非零元素保持原數組的順序,我只能想出在找到一個0時,逐個移動數組元素使得後一個元素覆蓋前一個元素,再將這個0移到後頭去。

My Code:

 1 public class Solution { 2     /* 3      * @param nums: an integer array 4      * @return:  5      */ 6     public void moveZeroes(int[] nums) { 7         // write your code here 8         //當數組為空白時直接返回 9         if(nums.length == 0) {10             return;11         }12         boolean b = true;13         //判斷數組是否全為0,若是,則直接返回14         for(int i=0; i<nums.length; i++) {15             if(nums[i] != 0) {16                 b = false;17             }18         }19         if(b == true) {20             return ;21         }22         23         int k = nums.length-1;24         int i = k;25         while(i >= 0) {26             //從後往前找元素值為0的數27             while(i>=0 && nums[i]!=0) {28                 i--;29             }30             if(i >= 0) {31                 int temp = nums[i];32                 for(int j=i; j<k; j++) {33                     nums[j] = nums[j+1];34                 }35                 nums[k] = temp;36                 k--;37             }38         }39     }40 }

 

LintCode之移動零

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.