LeetCode] [delete duplicates sort the array elements [&& remove specific double-pointer, in-place algorithm]

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:

Given array nums = [1,1,2],

Function should return a new length of 2, and the first two elements of the original array is modified to nums 1, 2.

You do not need to consider beyond the elements of the new array length behind.

Example 2:

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

New function should return the length 5 and the first five elements of the original array nums is modified to 0, 1, 2, 3, 4.

You do not need to consider beyond the elements of the new array length behind.

Source: stay button (LeetCode)
link:
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array

Analysis: The complexity of the space must be O (1)

Ordered arrays, it is possible to use a double pointer premise

Two pointers p1 and p2, the start point to the beginning of the original array

We assume that the last element of the array after the p1 point to remove duplicate numbers

P2 is assumed that points to the current need to remove the duplicate numbers

If the current p1 == p2, then p1 ++

If the current p1! = P2, then p1 ++, p2 point to the current value of the position p1 is placed

main idea:

Two pointers are shifted to the right, only when the two different pointer elements when, and only then into the different elements p1, then p1 ++

Such use of the original digital space, are in-place algorithm

Time complexity: O (N)

Space complexity: O (1)

class Solution {
public:
int removeDuplicates(vector<int>& v)
{
    int n=v.size();
    if(n==0)
        return 0;
    int k=0;
    for(int i=1;i<n;i++)
    {
        if(v[i]!=v[k])
        {
            k++;
            v[k]=v[i];
        }
    }
    return k+1;
}
};


给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

示例 1:

给定 nums = [3,2,2,3], val = 3,

函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。

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

示例 2:

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

函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。

注意这五个元素可为任意顺序。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-element

分析:和第一题思路一模一样,只是移动的条件由两个元素是否相等边除了元素是否等于特定元素

时间复杂度:O(N)

空间复杂度:O(1)

class Solution {
public:
int removeElement(vector<int>& v, int x)
{
    int n=v.size();
    if(n==0)
        return 0;
    int i=0;
    for(int j=0;j<n;j++)
    {
        if(v[j]!=x)
        {
            v[i++]=v[j];
        }
    }
    return i;
}
};


Guess you like

Origin www.cnblogs.com/yinbiao/p/11347937.html