『LeetCode題刷——Java實現』「27. Remove Element(刪除數組中指定元素)」

「27. Remove Element(刪除數組中指定元素)」



Question:

Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Translate:

在一個數組裏面移除指定 value,並且返回新的數組長度。 這題唯一需要注意的地方在於 in place,不能新建另一個數組。


Problem-solving ideas:

使用兩個遊標 i 和 j,遍歷數組,遇上非 value 則用 j 記錄位置,同時遞增 i,直到下一個非 value 出現,將此時 i 位置對應的值複製到 j 位置上,增加 j,重複上述過程直到遍歷結束。此時返回 j 的值即爲新的數組長度。


The code:

class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        int j = 0; //j用來記錄非value的位置
        /**
        * 從左邊開始遍歷數組,當前元素如果等於value(即nums[i]==value),則繼續執行,
        * 反之,若爲非value,則將此時 i 位置對應的值複製到 j 位置上。
        * 
        */
        for (i=0; i<nums.length; i++) {
            if (nums[i] == val) { //若當前元素與指定值value相等,則刪除。
                continue;
            } else {
                nums[j] = nums[i]; //將 i 位置對應的值複製到 j 位置上。
                j ++;
            }
        }
        return j;
    }
}


完整實現示例:

/**
 * Given an array and a value, remove all instances of that value in place and return the new length. 
 * The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
 * 解題思路:使用兩個遊標i和j,遍歷數組,遇上非value則用j記錄位置,同時遞增i,直到下一個非value出現,將此時i對應的值複製到j位置上,
 * 增加j,重複上述過程直到遍歷結束。此時返回j的值即爲新的數組長度。
 * @author 櫻木天亥
 */
public class Solution {

    public static void main(String[] args) {
        int[] arr = {1,2,2,3,2,4};
        System.out.println("新數組的長度爲:" + deleteElement(arr, 2));
    }

    public static int removeElement(int[] arr, int value) {
        int i = 0;
        int j = 0; //用來記錄非value的位置
         /**
        * 從左邊開始遍歷數組,當前元素如果等於value(即nums[i]==value),則繼續執行,
        * 反之,若爲非value,則將此時 i 位置對應的值複製到 j 位置上
        * 
        */
        for (i=0; i<arr.length; i++) {
            if(arr[i] == value) { //當前元素與指定值value相等,則刪除
                continue;
            } else {
                arr[j] = arr[i];
                j ++;
            }
        }
        return j;
    }
}


Performance:

這裏寫圖片描述


特別聲明:

歡迎轉載,轉載請註明出處「https://blog.csdn.net/Big_Rotor/article/details/79830708

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章