c++ 从排序数组中删除重复项

eyh26e7m  于 2023-05-08  发布在  其他
关注(0)|答案(6)|浏览(120)

**Qus:**从Sorted Array中删除重复项给定一个排序数组,在适当的位置删除重复项,使每个元素只出现一次,并返回新的长度。

请注意,即使我们希望您返回新的长度,也要确保在适当的位置更改原始数组
不要为另一个数组分配额外的空间,必须在具有常量内存的位置执行此操作。
我试着遵循代码,有人能帮助我哪里出错了吗??

#include<iostream>
    #include<vector>
    using namespace std;

    int removeDuplicates(vector<int> &A) {
        int m=A.size();
        if(m<=1) return m;
        vector<int> :: iterator i=A.begin();
        vector<int> :: iterator j=A.begin()+1;
        vector<int> :: iterator temp;
        while(i!=A.end() && j!=A.end())
        {
            while(j!=A.end() && *i == *j)
            {
                temp=j;
                j++;
                A.erase(temp);
            }
            i=j;
            j++;
        }
        return A.size();
    }

    int main()
    {
        vector<int> vec={0,0,0,0,0,0,0,4,4,7,7,7,7,9};
        cout<<"ans="<<removeDuplicates(vec);
        return 0;
    }
dffbzjpn

dffbzjpn1#

当你增加j,然后erase的元素,从j+1开始的元素被向下移动。通过递增跳过了一个元素。
更好的方法是简单地将非重复元素从一个迭代器复制到另一个迭代器,并在主循环结束时设置新的长度。时间复杂度为O(n^2),时间复杂度为O(n^2)。

unhi4e5o

unhi4e5o2#

我想这就是你需要的。这个函数循环数组从尾部到头部,并计算相同的值。然后在不唯一的值上执行已经唯一的值的移位。它不会改变vector的实际大小,因为它可能涉及vector内部内存的重新分配。

int removeDuplicates(vector<int> &vec) {
    int currentVal = vec.size() - 1;
    int uniqueNumber = 0;

    while (currentVal >= 0) {
        ++uniqueNumber;
        int sameVal = currentVal;
        while (sameVal > 0 && vec[sameVal - 1] == vec[currentVal])
            --sameVal;

        int shiftSize = uniqueNumber;
        for (int k = 1; k < shiftSize; ++k) {
            vec[sameVal + k] = vec[currentVal + k];
        }

        currentVal = sameVal - 1;
    }
    return uniqueNumber;
}
tkqqtvp1

tkqqtvp13#

要求您使用数组。虽然向量在很多方面都很相似,但它并不相同。看看下面的示例代码。
此外,还要求您保持分配的内存相同。你不能保证使用vector,一旦你添加/删除元素,它的大小就可以增长/收缩,当一个元素被删除时,vector后面的数组中的数据将被重新分配和重写。

int main()
{

    int arr[14] = {0,0,0,0,0,4,4,4,4,5,5,5,7,9};
    int last_non_duplicate_index = 0;
    int current_index = 0;
    int size = 14;
    int new_size = size;
    bool is_last_value = false;

    // you can use for interchangeably
    while(!is_last_value)
    {
        current_index++; // move one position ahead
        if(current_index < size) // out of bonds check
        {
            if(arr[last_non_duplicate_index] != arr[current_index]) // value at position of current index is different
            {
                last_non_duplicate_index++; // increase index of the last value which was not a duplicate by one
                arr[last_non_duplicate_index] = arr[current_index]; // write at that index 
                // e.g. if last index was 0 -> increase it to 1 and rewrite whatsever under arr[1] (current index)
            }
            else // values are the same
            { 
                new_size--; // devrease the size
            }
        }
        else
        {
            is_last_value = true; // current_index >= size -> out of bonds
        }
    }

    for (int i = 0; i < new_size; i++)
    {
        std::cout << "arr[" << i << "]" << " = " << arr[i] << std::endl;
    }
    std::cout << "New size: " << new_size << std::endl;
    return 0;
}
piah890a

piah890a4#

#TC : O(n)
#SC : O(1)

def removeDuplicates(arr,n):
    
    # If array has no elements or only one element, return n
    if (n==0 and n==1):
        return n 
    # arr = [1,2,2,3,4,4,4,5,5]
    # When i = 0, j= 0 arr=[1,2,2,3,4,4,4,5,5], arr[0] != arr[1], hence arr[0] = arr[0] and j =1, Increment i
    # When i = 1, j = 1 arr[j] =[1,2,2,3,4,4,4,5,5]. arr[1] == arr[2], hence increment i
    # When i = 2, j = 1 arr[j] = [1,2,2,3,4,4,4,5,5] arr[2] != arr[3], hence arr[1] = arr[2] j = 2, increment i
    # When i =3, j = 2 arr[j] = [1,2,3,3,4,4,4,5,5] arr[3] != arr[4], hence arr[2] = arr[3] and j = 3, Increment i
    # When i = 4, j = 3 arr[j] =[1,2,3,3,4,4,4,5,5] arr[4] == arr[5], hence increment i
    # When i = 5, j = 3 arr[j] = [1,2,3,3,4,4,4,5,5] arr[5] == arr[6], hence increment i
    # When i = 6, j = 3 arr[j] = [1,2,3,4,4,4,4,5,5] arr[6] != arr[7], hence arr[3] = arr[6] and j = 4, Increment i
    # When i = 7, j= 4 arr[j] = [1,2,3,4,4,4,5,5] arr[7] == arr[8], hence Increment i
   # End of for loop
     
    j = 0
    for i in range(0,n-1):
        if arr[i] != arr[i+1]:
            arr[j] = arr[i] 
            j = j + 1
            
    # Check for the last index element and copy it to a[j]. Increment the j and return j
    
    # When j = 4 arr[j] = [1,2,3,4,5,4,4,5,5] increment j
    # j = 5
    arr[j] = arr[n-1]
    j = j + 1
    return j 
if __name__=="__main__":
    arr = [1,2,2,3,4,4,4,5,5]
    #arr = [1,1,2]
    #arr = [2,2,2,2,2]
    n = len(arr)
    print(removeDuplicates(arr,n))
atmip9wb

atmip9wb5#

//In javascript
let arr=[1,1,2,2,2,3,3,5,5,5,5,5,8,8,9,9],arr1=[];
for(let i=0;i<arr.length;i++)
{
if(arr[i]!=arr[i+1])
arr1.push(arr[i]);
}
console.log(arr1);
6kkfgxo0

6kkfgxo06#

你可以这样使用迭代器:

#include<iostream>
#include<vector>

using namespace std;

int removeDuplicates(vector<int> &A) {
    int m = A.size();
    if(m <= 1) return m;

    for (auto it1 = A.begin(); it1 != A.end(); it1++) {
        for (auto it2 = it1 + 1; it2 != A.end();) {
            if (*it1 == *it2) {
                it2 = A.erase(it2);
            } else {
                it2++;
            }
        }
    }

    return A.size();
}

int main()
{
    vector<int> vec = { 0, 0, 0, 0, 0, 0, 0, 4, 4, 7, 7, 7, 7, 9 };
    cout << "ans=" << removeDuplicates(vec);
    return 0;
}

相关问题