【问题标题】:Find maximum non contiguous subarray that respect a specific rule查找遵守特定规则的最大非连续子数组
【发布时间】:2018-05-23 00:19:05
【问题描述】:

给定这两个数组:

[5, 3, 4, 1, 2]

[1, 3, 2, 4, 5]

找出两个数组中元素索引为新月顺序的最大子序列:

示例:[3, 4] 这是一个答案,因为索引在两个数组中都是新月形的。 (与[1, 2] 相同)。因此,答案[3, 4, 1] 的子序列是错误的,因为索引是第一个数组中的新月,而不是第二个。

程序的输出应该是最大非连续子数组的长度。

这是我为解决这个问题而编写的代码,但它只需要第一个子数组,我很难生成其他可能性

vector<pair<int, double>> esq;
vector<pair<int, double>> dir;
// N is the size of esq and dir
// pair<int, double> where int is the key (show in the example array) and double is the value, used for sort previously.
int cont = 1;
for (int i = 0; i < N - 1; i++)
{
    int cont_aux = 1;
    pair<int, double> pivot = esq[i];
    auto it_dir = find_if(dir.begin(), dir.end(), [&pivot](const pair<int, double> &p) { return p.first == pivot.first; });
    int last_index = it_dir - dir.begin();

    for (int j = 0; j < N; j++)
    {
        pair<int, double> actual = esq[j];
        auto it = find_if(dir.begin(), dir.end(), [&actual](const pair<int, double> &p) { return p.first == actual.first; });
        int pos = it - dir.begin();

        if (pos >= last_index) {
            last_index = pos;
            cont_aux++;
        }
    }

    cont = max(cont, cont_aux);
}

cout << cont << endl;

【问题讨论】:

  • 用什么编程语言?
  • 任何语言,例如可以是 C++
  • Stack Overflow 非常注重代码,因此“任何语言”都不是我们可以回答的。如果您想要基于理论的解决方案,CS Site 更合适。
  • 感谢您的建议,请问可以使用 c++ 吗?
  • 你绝对可以使用 C++。花一些时间尝试并创建一个解决方案,然后根据您的尝试编辑您的问题。这不是免费的代码编写服务。你必须表明你致力于解决问题。

标签: c++ arrays sub-array


【解决方案1】:
lista_test = [5,3, 4,1,7, 2]
lista2_test = [5,1,3, 2, 4,7]

def max_nocontigoous(list_a,list_b):
    #lets suppose that the list is ordered.
    count_i = 0
    count_j_previous = 0
    count_j = 0 
    counter_exclusive = 0
    listDouble = list()
    indice_real = 0
    for i in range(len(list_a)):
        try:
            element_a = list_a[i]
            if element_a in list_b and list_b.index(element_a)>=count_j:
                if count_j_previous != count_j:
                    listDouble[len(listDouble)-1].append(element_a)
                    count_j_previous = count_j
                else:
                    if(i == 0):
                        count_j_previous  -= 1
                    listDouble.append([element_a])
            else:
                listDouble.append([element_a])
                count_j_previous = count_j
                count_j = list_b.index(element_a)   
        except IndexError:
            print("Error in: " +str(i) + " iteration")
    return listDouble

print(max_nocontigoous(lista_test,lista2_test))

请注意,在我的例子中,我认为第一个数组或列表只能是一个列表,其值是有序且连续的。我刚刚考虑过它,因为我遵循了您的示例,其中您有一个具有连续排序值的数组,而下一个数组不一定是连续的。 好看!

【讨论】:

    猜你喜欢
    • 2013-09-13
    • 2010-09-17
    • 2021-01-15
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多