我用JS刷LeetCode | Day 7 | Remove Duplicates from Sorted Array

我用JS刷LeetCode | Day 7 | Remove Duplicates from Sorted Arrayjavascript

刪除排序數組中的重複項:

說明:現階段的解題暫未考慮複雜度問題

首發地址:http://www.brandhuang.com/article/1583928356964前端

Question:

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

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

中文題目:

給定一個排序數組,你須要在 原地 刪除重複出現的元素,使得每一個元素只出現一次,返回移除後數組的新長度。微信

不要使用額外的數組空間,你必須在原地修改輸入數組 並在使用 O(1) 額外空間的條件下完成。app

Example:this

Given nums = [1,1,2],

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.


Given nums = [0,0,1,1,1,2,2,3,3,4],

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.

我的分析:

  1. 這道題就是我平時常常用到的數組去重,除了題目加了一個限制條件:「不要使用額外的數組空間,你必須在原地修改輸入數組」
  2. 我給出的答案是一種在 es5 中比較常見的一種 for循環 方式(答案一),比較相鄰兩元素是否相同,若是相同則從數組中刪去第二個
  3. 看了大神們的答案,題目中提到 「你不須要考慮數組中超出新長度後面的元素。」,因此有了 答案二, 直接從第 0 位開始替換原數組中的值。

Answer:

// 答案一
var removeDuplicates = function(arr) {
    for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[i] === arr[j]){         
                    arr.splice(j,1);
                    j--;
                }
            }
        }
    return arr.length
};
// 答案二
var removeDuplicates = function(arr) {
      var i = 0;
    arr.forEach(function (elem) {
        if (elem !== arr[i]) {
            arr[++i] = elem;
        }
    });
    return i + 1;
};

其餘:

本題更多 JavaScript 解析,點擊連接訪問對應的答案:https://leetcode.comes5

若有興趣掃碼或微信搜索「九零後重慶崽兒」,咱們一塊兒學前端。spa

brandQRcode.jpg

相關文章
相關標籤/搜索