Leetcode--283. 移动零
生活随笔
收集整理的這篇文章主要介紹了
Leetcode--283. 移动零
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)數(shù)組 nums,編寫一個(gè)函數(shù)將所有 0 移動(dòng)到數(shù)組的末尾,同時(shí)保持非零元素的相對(duì)順序。
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說(shuō)明:
必須在原數(shù)組上操作,不能拷貝額外的數(shù)組。
盡量減少操作次數(shù)。
class Solution {
? ? public void moveZeroes(int[] nums) {
? ? ? ? ?int count = 0;
? ? ? ? for(int i = 0; i < nums.length; i++) {
? ? ? ? ? ? if(nums[i] == 0) {
? ? ? ? ? ? ? ? count++;
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? nums[i - count] = nums[i];
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? for(int i = nums.length - count; i < nums.length; i++) {
? ? ? ? ? ? nums[i] = 0;
? ? ? ? }
? ? }
}
總結(jié)
以上是生活随笔為你收集整理的Leetcode--283. 移动零的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【剑指offer】面试题53 - 1:在
- 下一篇: NIO的多线程优化