c++ - 递增序列 C++

标签 c++ c++11 sequence

我尝试在 CodeFights 上解决这个挑战,但没有成功。我最好的解决方案得到了 25/26(上次测试超过了时间限制)但我删除了它,因为我昨天试过了(它是 O(n^2))。现在我在 O(n) 中尝试了一个新的。我很累,我今天很想完成这个,所以请帮助我。

声明如下: 给定一个整数序列作为数组,确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列。

例子

For sequence = [1, 3, 2, 1], the output should be
almostIncreasingSequence(sequence) = false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
almostIncreasingSequence(sequence) = true.

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

这是我到目前为止的代码...(糟糕的代码):

#include <iostream>
#include <vector>

#include <algorithm>

bool almostIncreasingSequence(std::vector<int> sequence) 
{
    int count = 0;


    for(int i = 0; i < sequence.size()-1; i++)
    {
        if(sequence[i] > sequence[i+1])
        {
            count++;
            sequence.erase(sequence.begin(), sequence.begin() + i);
            i--;
        }
        if(count == 2)
            return false;
    }
    return true;
}

int main()
{
    std::cout << std::endl;
    return 0;
}

最佳答案

这是一个运行时复杂度为 O(N) 的 C++11 解决方案:

constexpr auto Max = std::numeric_limits<std::size_t>::max();
bool is_sorted_but_skip(const std::vector<int>& vec, std::size_t index = Max){
    auto Start = index == 0 ? 1 : 0;
    auto prev = vec[Start];
    for(std::size_t i = Start + 1; i < vec.size(); i++){
        if(i == index) continue;
        if(prev >= vec[i]) return false;
        prev = vec[i];
    }
    return true;
}

bool almostIncreasingSequence(std::vector<int> v) 
{
    auto iter = std::adjacent_find(v.begin(), v.end(), [](int L, int R){ return L >= R; });
    if(is_sorted_but_skip(v, std::distance(v.begin(), iter)))
        return true;
    return is_sorted_but_skip(v, std::distance(v.begin(), std::next(iter)));
}

我们使用 std::adjacent_find查找第一个元素,iter 大于或等于它的下一个元素。然后我们在跳过 iter 的位置时检查序列是否严格排序。

否则,我们会在跳过 iter+1 的位置时检查序列是否严格排序

最坏情况复杂度:3 线性扫描

Demo

关于c++ - 递增序列 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635356/

相关文章:

c++ - C++ 如何通过调用 object.method() 在 object1 的上下文中调用类 method()

c++ - 如何将 BMP 像素值读入数组?

c++ - 列表初始化中多个模板化构造函数的重载规则

c++ - 为什么 gcc 不在 std::uninitialized_copy 中使用 memmove?

java - Hibernate 在使用 Oracle 序列时不生成标识符

c++ - 在注入(inject)另一个进程时控制 dllmain() 调用的顺序

c++ - 查找数组总数

c++ - 在基于范围的循环期间将元素添加到 vector c++11

c - 如何在 C 中读取和存储字节序列( Short 数组)中的位以通过网络发送数据

arrays - Swift 序列前缀(而 :) return not all elements