国产探花免费观看_亚洲丰满少妇自慰呻吟_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;    }}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丰城市| 都江堰市| 孟州市| 武夷山市| 宣恩县| 抚顺县| 灯塔市| 韩城市| 建阳市| 安龙县| 南木林县| 永定县| 镇原县| 石景山区| 安康市| 枣庄市| 东港市| 宜川县| 鞍山市| 泰宁县| 左权县| 开平市| 商都县| 邵阳市| 南木林县| 麻江县| 平江县| 商丘市| 湄潭县| 双江| 高陵县| 滨海县| 棋牌| 盐亭县| 崇仁县| 囊谦县| 育儿| 乌拉特前旗| 同仁县| 遵化市| 崇左市|