查找遵循特定规则的最大非连续子数组

时间:2017-12-08 17:48:01

标签: c++ arrays sub-array

鉴于这两个阵列:

[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;

1 个答案:

答案 0 :(得分:0)

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))

请注意,我认为我的第一个数组或列表只能是一个列表,其值按顺序连续。我刚刚考虑过它,因为我已经按照你的例子,你有一个连续值的数组,下一个数组可能不一定是连续的。 好看!