I use js to brush leetcode | day 7 | remove duplicates from sorted array

Time:2021-9-22

I use js to brush leetcode | day 7 | remove duplicates from sorted array

Remove duplicates from sort array:

Note: the complexity problem is not considered at this stage

Starting address: 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.

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

Chinese Title:

Given a sorted array, you need to delete the repeated elements in place, so that each element appears only once, and return the new length of the array after removal.

Do not use additional array space. You must modify the input array in place and complete it with O (1) additional space.

Example:


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.

Personal analysis:

  1. This problem is the array de duplication I often use, except that the problem adds a restriction:"Do not use additional array space. You must modify the input array in place"
  2. The answer I give is ines5A common one inFor loopMode(Answer one),Compare whether two adjacent elements are the same. If they are the same, delete the second element from the array
  3. After reading the answers of the great gods, it is mentioned in the title"You don't need to consider the elements in the array that exceed the new length.", so yesAnswer two, replace the values in the original array directly from bit 0.

Answer:

//Answer one
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
};
//Answer two
var removeDuplicates = function(arr) {
      var i = 0;
    arr.forEach(function (elem) {
        if (elem !== arr[i]) {
            arr[++i] = elem;
        }
    });
    return i + 1;
};

other:

More questionsJavaScriptAnalyze and click the link to access the corresponding answer: https://leetcode.com

If you are interested in scanning code or searching “Chongqing cubs after 90” on wechat, let’s learn the front end together.

I use js to brush leetcode | day 7 | remove duplicates from sorted array