java初始化數組賦值「java清空數組的方法」

26. Remove Duplicates from Sorted Array

Easy

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: Your function should return length = 2
, with the first two elements of nums
 being 1
 and 2 respectively. It doesn't matter what you leave beyond the returned length.

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4]
Explanation: Your function should return length = 5
, with the first five elements of nums
 being modified to 0
, 1
, 2
, 3
, and 4 respectively. It doesn't matter what values are set beyond the returned length.

Constraints:

  • 0 <= nums.length <= 3 * 104
  • -104 <= nums[i] <= 104
  • nums is sorted in ascending order.

給定一個有序數組,刪除重複內容,使每個元素只出現一次,並返回新的長度。

題目要求不要為其他數組分配額外的空間,您必須通過在 O(1)額外的內存中就地修改輸入數組來實現這一點。

解題思路:

這是一道難度簡單的題目,已知條件數組是已排序的,且不能新建數組,這就是告訴我們除了創建數組指針只能改變給定數組來得到結果。

class Solution {
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return 0; //首先排除邊界的case
        }      
        int counter = 0, i = 1; //定義兩個指針,counter代表當前去重的長度,i是遍歷的指針,為什麼i是從1開始? 因為起始位置的數組元素已經計算到結果中,所以開始從二個元素遍歷
        while(i < n) {
            if (nums[counter] == nums[i]) { //判斷當前遍歷的數組元素和去重後的最大數組元素是否相同,如果相同則繼續遍歷,不做任何操作。 
                i++;
            } else { //如果不同,則將數組當前遍歷的元素替換到去重數組
                counter++; //在替換前首先將去重指針後移一位
                nums[counter] = nums[i];
                i++; //繼續遍歷
            }
        }
        return counter + 1; //counter是去重指針的最後一位,所以長度需要加1
    }
}

總結:這類數組去重的題會經常出現在面試環節中(3sum),看到數組去重我們就要想到對數組先進行排序,然後通過一個n的遍歷就能解決問題。

另外就是不佔用額外空間,只能新建指針和當前給定的數組來操作。

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/234872.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-12 11:49
下一篇 2024-12-12 11:49

相關推薦

發表回復

登錄後才能評論