当前位置: 首页 > 知识库问答 >
问题:

如何在Java中从数组中提取最长的连续整数序列?

严高峻
2023-03-14

我想显示给定数组int中的所有连续序列。最后,我想用文本显示最长的序列。

  • 我对数组进行了排序,找到了所有序列

以下仅是一小段代码,因为我知道其余部分不起作用:

int[] myArray = {202,203,204,205,206, 100, 1, 3, 200, 2, 4, 201, 5};
ArrayList<Integer> secuence = new ArrayList<>();
Arrays.sort(myArray);

for (int i = 0; i < myArray.length - 1; i++) {
  if ((myArray[i] + 1) == myArray[i + 1] || (myArray[i] - 1) == myArray[i - 1]) {
    secuence.add(myArray[i]);
  }
}

我尝试了许多不同的方法,但无法弄清楚。

共有2个答案

单于煌
2023-03-14

我的解决方案如下:

  1. 一个连续的序列(我们要找到的)是至少2个连续的整数s(对)
  2. List
  3. 要返回所有查找序列,您需要一个结果List包含0个或多个Lists
  4. 要检查连续性,您需要当前先前元素

应用的逻辑(如果):

  1. 如果当前==前1,则找到连续性,否则现有的连续序列被破坏
  2. 如果一个序列至少有2个元素,即sequence.size()

迭代元素(循环):

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class ConsecutiveSequenceFinder {

    private int[] unsortedNumbers;

    public ConsecutiveSequenceFinder(int[] numbers) {
        this.unsortedNumbers = numbers;
    }

    public int[] sorted() {
        int[] sortedNumbers = Arrays.copyOf(this.unsortedNumbers, this.unsortedNumbers.length);
        Arrays.sort(sortedNumbers);
        return sortedNumbers;
    }

    public List<List<Integer>> findSequences() {
        // one sequence is List of integers; thus list of sequences is list of list of integers
        List<List<Integer>> foundSequences = new ArrayList<>();
        // first we sort the array
        int[] ascending = this.sorted();
        // this working variable will hold the currently found sequence
        List<Integer> sequence = new ArrayList<Integer>();
        Integer previous = null;
        System.out.println("Finding sequences ..");
        for (int current : ascending) {
            // check if current value is first or one more than (consecutive to) previous
            if (previous == null || current == previous + 1) {
                sequence.add(current);
                previous = current;
            } else {
                System.out.printf("\tsequence of %d consecutive is broken at: %d\n", sequence.size(), current);
                // if sequence found (at least a pair) then add
                if (sequence.size() > 1) {
                    foundSequences.add(sequence);
                }
                // and finally prepare a new sequence, to collect fresh again
                sequence = new ArrayList<>();
                previous = null;
            }
        }
        // if sequence left, then add
        if (sequence.size() > 1) {
            System.out.printf("\tsequence of %d consecutive was completed with last array element\n", sequence.size());
            foundSequences.add(sequence);
        }
        return foundSequences;
    }

    public static void main (String[] args) throws java.lang.Exception {
        // demo numbers
        int[] values = {202,203,204,205,206, 100, 1, 3, 200, 2, 4, 201, 5};
        // starting demo
        System.out.println("Input: " + Arrays.toString(values));
        ConsecutiveSequenceFinder finder = new ConsecutiveSequenceFinder(values);
        System.out.println("Sorted: " + Arrays.toString(finder.sorted()));
        List<List<Integer>> foundSequences = finder.findSequences();
        System.out.println("Found sequences: " + foundSequences.size());
        // print for each sequence the size and its elements
        for (List<Integer> sequence : foundSequences) {
            System.out.printf("\t %d elements: %s\n",sequence.size(), sequence.toString());
        }
        // check for each sequence if it is the longest
        List<Integer> longestSequence = new ArrayList<>();
        for (List<Integer> sequence : foundSequences) {
            if (sequence.size() > longestSequence.size()) {
                longestSequence = sequence;
            }
        }
        System.out.printf("Longest sequence has %d elements: %s\n",longestSequence.size(), longestSequence.toString());
    }
}
Input: [202, 203, 204, 205, 206, 100, 1, 3, 200, 2, 4, 201, 5]
Sorted: [1, 2, 3, 4, 5, 100, 200, 201, 202, 203, 204, 205, 206]
Finding sequences ..
    sequence of 5 consecutive is broken at: 100
    sequence of 7 consecutive was completed with last array element
Found sequences: 2
     5 elements: [1, 2, 3, 4, 5]
     7 elements: [200, 201, 202, 203, 204, 205, 206]
Longest sequence has 7 elements: [200, 201, 202, 203, 204, 205, 206]

Process finished with exit code 0

白芷阳
2023-03-14

几句评论、建议:

  • 由于排序()按递增顺序对数组排序,实际上不必检查递减元素
  • 为了找到“任何”最重要的东西,您需要存储迄今为止找到的“任何”最重要的东西,以及当前的候选对象。这也适用于查找最大元素或连续元素的最长序列
  • 对于处理数组的子部分,不必制作元素的实际副本,只需存储开始索引和结束索引或长度即可

将它们放在一起:

var myArray = [202,203,204,205,206, 100, 1, 3, 200, 2, 4, 201, 5];
myArray.sort((a,b)=>a-b);
console.log("Sorted array:",...myArray);

var longstart=0;
var longlength=0;

var currstart=0;
while(currstart<myArray.length){
  var currlength=0;
  while(currstart+currlength<myArray.length
    && myArray[currstart]+currlength==myArray[currstart+currlength])
    currlength++;
  if(currlength>longlength){
    longlength=currlength;
    longstart=currstart;
  }
  console.log("Sequence:",...myArray.slice(currstart,currstart+currlength));
  currstart+=currlength;
}
console.log("Longest:",...myArray.slice(longstart,longstart+longlength));
 类似资料:
  • 我为这个问题写了一个方法:输入:整数数组返回:最长连续整数序列的长度。like:对于{9,1,2,3},返回3,因为{1,2,3} 这个方法运行得不好。希望有人能帮我调试。 非常感谢!!!

  • 本文向大家介绍JavaScript实现列出数组中最长的连续数,包括了JavaScript实现列出数组中最长的连续数的使用技巧和注意事项,需要的朋友参考一下 原始题目: 给定一个无序的整数序列, 找最长的连续数字序列。 例如: 给定[100, 4, 200, 1, 3, 2], 最长的连续数字序列是[1, 2, 3, 4]。 小菜给出的解法:   调用说明:      方法名称:         

  • 问题内容: 我有一个String变量(基本上是一个英语句子,带有未指定数量的数字),我想将所有数字提取到一个整数数组中。我想知道是否有使用正则表达式的快速解决方案? 我使用了Sean的解决方案,并对其进行了一些更改: 问题答案: …打印和。 -?匹配前导负号-可选。 d匹配一个数字,但是我们需要像Java String中那样编写。因此, d +匹配1个或多个数字。

  • 本文向大家介绍C ++中数组中存在的最大连续数,包括了C ++中数组中存在的最大连续数的使用技巧和注意事项,需要的朋友参考一下 给定一个正整数数组。目的是找到其中存在的最大连续数。首先,我们将对数组进行排序,然后比较相邻元素arr [j] == arr [i] +1(j = i + 1),如果差为1,则递增计数,索引i ++,j ++,否则更改计数= 1 。将到目前为止找到的最大计数存储在maxc

  • 问题内容: 我有一个变量,如下所示: 该变量中包含许多城镇数据。如何有效地从数据中提取第三个元素?我,下面会是什么? 如果我想将两个值都存储在数组中怎么办?那是 我是Java的新手。我希望有一种不使用for循环的方法。 问题答案: 在较新的浏览器上,您可以使用,否则可以避免使用循环。 但是for循环更兼容。

  • 问题内容: 对于这个例子说,我有两个字段的表,和。 该表具有以下数据 我想回来 我想返回的结果是每个区域递增连续值的最长长度。对于。 我将如何在MS Sql 2005上执行此操作? 问题答案: 一种方法是使用遍历每一行的递归CTE。如果该行符合条件(增加同一区域的订单号),则将链长增加一。如果没有,则启动一个新链: SQL Fiddle的实时示例。 另一种方法是使用查询查找“中断”,即以相同区域的