【问题标题】:Create intervals in a sorted array在排序数组中创建间隔
【发布时间】:2017-10-30 16:40:46
【问题描述】:

假设我有一个{1, 2, 3, 4, 5, 7, 8, 9, 10, 15, 16, 21, 23, 25, 26} 的排序数组。 我想通过以下方式将这些元素放入间隔中:

1..5
7..10
15..16
21..21
23..23
25..26

实际上我有更大的数据,所以我需要一个运行时间好的算法。

我的想法如下: 将数组分成两部分,并用 4 个循环遍历数组。从 0 索引开始循环,从数组中间开始循环 2,从数组末尾开始循环 1。每个循环都会检查当前和下一个元素的 diff 是否为 1,如果是,则转到下一个元素,否则从前一个元素创建一个区间,并从下一个元素开始一个新区间。

我的问题是这是一个好方法,还是有更好的方法?请伪代码或java代码。

【问题讨论】:

  • 为什么不从索引 0 开始,做顺序循环并跟踪区间的第一个元素。
  • 你如何推导出区间?我没有看到任何模式。
  • 为什么所有的循环?这似乎是一个循环,从最后一个值 + 1 != 当前值开始有一个新的间隔。
  • 有给你间隔吗?您是否正在尝试编写一个以int[] originalArrayint[][] intervals(其中intervals[i].length == 2 表示所有i < intervals.length)作为参数的函数?请澄清哪些数据类型作为输入给出,以及哪些数据类型预期作为输出。另外,您是否尝试编写一种方法来执行此操作?你能分享一下你做了什么吗?
  • @Blake int[] 数组是输入,数字从 000006 到 999999。输出可以是 int[][]

标签: java intervals sortedlist


【解决方案1】:

线性解:

int intervalStart = a[0];
for (int i = 1; i < a.length; ++i) {
    if (a[i] > a[i-1] + 1) {
        outputInterval(intervalStart, a[i-1]);
        intervalStart = a[i];
    }
}
outputInterval(intervalStart, a[a.length-1]);

可运行版本:https://ideone.com/NZ2Uex

【讨论】:

    【解决方案2】:

    您可以考虑使用来自 Apache Commons 的 IntRanges 数组来表示这样的概念。

    是的,它需要一个第三方库,但毕竟是 Apache Commons。

    【讨论】:

      【解决方案3】:

      您正在尝试获取连续整数的列表。

      O(n) 中最简单和最天真的方法是做这样的事情:

      List<List<Integer>> list_of_sublists = new List<>(); // The list of sublists
      int lastElement = elements[0];
      List<Integer> subList = new List <>(); // The current sublist
      subList.add(lastElement);
      int i = 1; // We start with index 1 because index 0 is already done
      while (i < elements.length){
         int element = elements[i]
         if !(lastElement + 1 == element)){ //If not a consecutive we start a new list
             list_of_sublists.add(subList);
             subList = new List<>();
         }
         lastElement = element;
         subList.add(element);
         i ++;
      
      //We didn't add the last sublist
      list_of_sublists.add(subList);
      return list_of_sublists;
      

      您可以通过获取间隔并在每个间隔之后复制来轻松适应arrays

      【讨论】:

        【解决方案4】:

        另一个版本,有两个指针(python):

        def compress_to_range(vector):
            # O(n) in time, just one pass thru the list
            result = []
            i = 0
            while i < len(vector):
                j = i+1
                while j < len(vector) and vector[j] == vector[j-1]+1:
                    j += 1
                # j now points to the element outside the interval
                result.append([vector[i], vector[j-1]])
                i = j
        
            return result
        

        【讨论】:

          猜你喜欢
          • 2022-01-08
          • 1970-01-01
          • 2015-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-23
          相关资源
          最近更新 更多