国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

【leetcode】MoveZeroes

2019-11-14 15:35:25
字體:
來源:轉載
供稿:網友

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.

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.

一開始的想法是,遍歷數組,遇到0就往后移,一直移動最后一步。代碼如下

public class Solution {    public static void moveZeroes(int[] nums) {        for (int i = 0; i < nums.length; i++) {            if (nums[i] == 0 && i != (nums.length - 1)) {                for (int j = i; j < nums.length - 1; j++) {                    int temp = nums[j];                    nums[j] = nums[j + 1];                    nums[j + 1] = temp;                }            }        }    }}

但是,發現001這個測試用例不對。

恩,發現問題了,因為第一個數為0,第二個0就沒辦法移動到最后了。

換一種思路,不遍歷找0,而是遍歷找非0,遇到非0,且不在第一位,就往前移,直到它前面不是0為止。

public class Solution {    public static void moveZeroes(int[] nums) {        for (int i = 0; i < nums.length; i++) {            if (nums[i] != 0 && i != 0) {                for (int j = i; j > 0 && nums[j - 1] == 0; j--) {                    int temp = nums[j - 1];                    nums[j - 1] = nums[j];                    nums[j] = temp;                }            }        }    }}

這樣就解決了

其他方法

public static void moveZeroes(int[] nums) {        int i = 0, j = 0;        for (i = 0; i < nums.length; i++) {            if (nums[i] != 0) {                if (j != i) {                    nums[j] = nums[i];                    nums[j] = 0;                }                j++;            }        }    }

這種方法i遍歷數組,只有當i指向為非0時,且ji不同時,j后移,將j處的數改成i處的數,并使i處的數字為0,ij同步后移,而當i指向為0時,只有i后移,j仍然指向0處。

還有一種更簡單的方法

public void moveZeroes(int[] nums) {    if (nums == null || nums.length == 0) return;            int insertPos = 0;    for (int num: nums) {        if (num != 0) nums[insertPos++] = num;    }            while (insertPos < nums.length) {        nums[insertPos++] = 0;    }}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 瑞安市| 宝兴县| 林州市| 图们市| 遵义市| 娄烦县| 英德市| 公主岭市| 雷山县| 肥西县| 临城县| 乾安县| 凌云县| 星子县| 鹿泉市| 泸州市| 沂源县| 揭西县| 利津县| 荔波县| 酉阳| 娄底市| 托克托县| 麟游县| 迭部县| 河津市| 徐州市| 平和县| 樟树市| 东源县| 阜新| 那曲县| 晋州市| 海安县| 柳林县| 新田县| 四平市| 苍山县| 余庆县| 沁水县| 冷水江市|