Delete duplicates --leetcode algorithm to sort an array of questions

The title comes from leetcode

Subject description:

Given a sorted array, you need to remove the recurring elements in place, so that each element appears only once, after returning the new length of the array is removed.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

Example 1:

给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素。

Example 2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],

函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。

你不需要考虑数组中超出新长度后面的元素。

Description:

Why return value is an integer, but the answer is an array of output it?

Please note that the input array is passed by "reference" mode, which means to modify the input array is visible to the caller within the function.

You can imagine the internal operation is as follows:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

Problem-solving ideas:

1: Cycle the original array; if there is only one target at the current value of the array to determine if there is beyond a delete, or into the next cycle

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    for(let i = 0, l = nums.length; i < l; i++){
        while(nums.indexOf(nums[i]) > -1 && nums.indexOf(nums[i]) !== nums.lastIndexOf(nums[i])){
            nums.splice(nums.lastIndexOf(nums[i]),1)
        }
    }
    return nums.length;
};

2: using a two-hand method of
defining a pointer j, when the cyclic array if and ARR [j] is not the same value, j + 1; So finally j figure represents arr [0] is not the same worth Number ; then we need to return after j + 1

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    const len = nums.length;
    if(len === 0){
        return 0;
    }
    let j = 0;
    for(let i = 0; i < len; i++){
        if(nums[i] !== nums[j]){
            j += 1;
            nums[j] = nums[i];
        }
    }
    return j + 1;
};

Guess you like

Origin www.cnblogs.com/guojikun/p/11423229.html