如何在一个相当大的阵列中获得最大数量的连续整数(分布在多台机器上)

时间:2017-03-08 00:47:04

标签: arrays distributed-computing distributed-system system-design

我在接受采访时被问到这个问题。第一部分非常简单,我必须编写一个代码来获得数组中最大数量的连续整数。以下是我写的代码:

int count = 0, max = 0;
for(int i = 1; i < array.length; i++) {
    if((array[i - 1] + 1) == array[i])) //curr is consecutive to prev
          count++;
    else
          count = 0; //reset the counter as sequence is broken

    //Keep track of maximum
    if(count > max)
         max = count;
}

System.out.println(max); //print the length of largest consecutive integers

第二部分是跟进问题:

如何修改此逻辑以适用于存储在多台计算机中的阵列?

2 个答案:

答案 0 :(得分:0)

您可以使用Reduce Parallel Pattern

实施它

Python中的示例(抱歉是错误的命名):

def longest_seq(seq):

    Result = namedtuple("Result", ["left", "left_n", "max_n", "right", "right_n", "is_const"])

    def _longest_seq(seq):
        if 1 == len(seq):
            x = seq[0]
            return Result(left=x, left_n=1, max_n=1, is_const=True, right=x, right_n=1)

        l_res = _longest_seq(seq[0: int(len(seq) / 2)])
        r_res = _longest_seq(seq[int(len(seq) / 2): len(seq)])

        left_n = l_res.left_n + r_res.left_n if l_res.is_const and l_res.right == r_res.left else l_res.left_n
        right_n = r_res.right_n + l_res.right_n if r_res.is_const and r_res.left == l_res.right else r_res.right_n
        max_n = max(l_res.max_n, r_res.max_n, l_res.right_n + r_res.left_n if l_res.right == r_res.left else 0)
        is_const = l_res.is_const and r_res.is_const and l_res.right == r_res.left

        return Result(left=l_res.left,
                      left_n=left_n,
                      max_n=max_n,
                      right=r_res.right,
                      right_n=right_n,
                      is_const=is_const)

    return _longest_seq(seq).max_n

答案 1 :(得分:0)

假设我们按顺序从左到右分配整个数组。例如,对于仅两台计算机(machine1machine2),我们会将数组0.... i分发到machine1,将i + 1....n分发到machine2。从每台机器,我们可以返回几个附加信息以及本地最大值。

class result {
    public int machineId;
    public int maxSoFar; // the max value as your code
    public int leftElement; // the leftmost element
    public int leftLength; // number of times the leftElement appears consecutively in left
    public int rightElement; // the rightmost element
    public int rightLength;  // number of times the rightElement appears consecutively in right
};

在合并两台机器的结果期间,对于machineId连续的任何两台机器(例如3和4),我们可以像这样最大化 -

return Math.max(((machine1.rightElement == machine2.leftElement) ? machine1.rightLength + machine2.leftLength : 0), 
                  Math.max(machine1.maxSoFar, machine2.maxSoFar));
相关问题