简体   繁体   English

编写一个程序来查找整数数组中最长的连续序列的长度?

[英]Write a program to find length of longest consecutive sequence in array of integers?

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. 例如,给定[100,4,2,1,3,2],最长的连续元素序列是[1,2,3,4]。

 public class Array {
  public static void main(String args[]){

    int a[]={10,15,1,2,3,4,5,11,12};

    int b=1;
    int c=0;
    for(int i=0;i<a.length-1;i++){

       if(a[i]-a[i+1]==-1){

         b=b+1;
         c=c+1;
         if(b>=c)
       {

       System.out.println(a[i]);

         }
         else{
             b=0;
         } 

    }

}
}
}

But i am getting output as 1 2 3 4 11 whereas the output should be 1 2 3 4 5. 但我的输出为1 2 3 4 11,而输出应为1 2 3 4 5。

How to get the required output,whats the mistake in a code? 如何获得所需的输出,是什么代码中的错误?

You can try this out: 你可以尝试一下:

int[] array = {10,15,1,2,3,4,5,11,12};
List<Integer> tempList = new ArrayList<>(); // prepare temp list for later use
List<List<Integer>> arrays = new ArrayList<>(); // used to store the sequences
int lastNum = array[0]; // get the fist number for compasion in loop
tempList.add(lastNum);
for (int i = 1; i < array.length; i++) {
    if (array[i]-1 == lastNum) { // check for sequence (e.g fist num was 12,
      // current number is 13, so 13-1 = 12, 
      // so it has the sequence), then store the number
        tempList.add(array[i]); // store it to the temp list
        lastNum = array[i]; // keep current number for the next
    } else { // if it has not the sequence, start the new sequence
        arrays.add(tempList); // fist store the last sequence
        tempList = new ArrayList() // clear for the next sequence
        lastNum = array[i]; // init the lastNumnber
        tempList.add(lastNum);
    }
}
// now iterate for the longest array
// craete an empty array to store the longest
List<Integer> longestLength = new ArrayList<>();
for (List<Integer> arr : arrays) {
    if (arr.size() > longestLength.size()) {
        // check if the current array hase the longest size than the last one
        // if yes, update the last one
        longestLength = arr;
    }
}
// at the end print the result.
System.out.println("longestLength = " + longestLength);

The Result: 结果:

longestLength = [1, 2, 3, 4, 5]

Try this code 试试这个代码

public class Array {
      public static void main(String args[]){

        int a[]={10,15,1,2,3,4,5,11,12};

        int ms=0;                  // starting point of max subseq
        int me=0;                   //ending point of max subseq
        int cs=0,ce=0;              //starting and ending  point of current subseq
        int max=0,c=0;           // length of max and current subseq
        for(int i=0;i<a.length-1;i++){

           if(a[i]-a[i+1]==-1){

             if(c==0)             //we found the first element of a subseq
             {
               cs=i;ce=i+1;c=2;   //made the starting of currrent seq=i, end=i+1 and length=2
              }
             else             // element is a part of subsequence but not first elem
              {
               ce=i+1;c++;     // increased current ending point
              } 

              if(c>max)          // if lenth of current subseq is now largest then update staring and ending points of max
               {
                   max=c;
                   ms=cs;
                   me=ce;
               }
             }
             else             // subseq ended
             {
             cs=0;
             ce=0;
             c=0;
              }
      }
        for(i=ms;i<=me;i++)           //printing max subsequence
         System.out.println(a[i]);
    }
    }

Note: see comments for description 注意:请参阅注释以获取说明

Your code should work if you sort the array first. 如果首先对数组进行排序,则代码应该可以正常工 Have you tried that? 你试过吗?

import java.util.*;
    Arrays.sort(a);

then 然后

    if(a[i]+1==a[i+1])
          //print it 
     else
        {
            System.out.print(a[i]);
            i=a.length;
        }//stop the loop
class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int a[]={10,15,1,2,3,4,5,11,12};
        Arrays.sort(a);
        ArrayList<Integer>output = new ArrayList<Integer>();
        ArrayList<Integer>temp = new ArrayList<Integer>();
        for(int i =1; i<a.length; i++){
            //If elements have difference of one, add them to temp Arraylist
            if(a[i-1] + 1 == a[i]){
                temp.add(a[i-1]);
            }
            else{
                //Add the last consecutive element 
                temp.add(a[i-1]);

                //If temp is lager then output
                if(temp.size() > output.size()){
                    output = (ArrayList<Integer>) temp.clone();
                        temp.clear();
                }           
            }
        }

        //Outside for loop, making sure the output is the longer list. This is to handle the case where the consecutive sequence is towards the end of the array
        if(temp.size() > output.size()){
            output = (ArrayList<Integer>) temp.clone();System.out.println("after clone outside for " + output.toString());
        }   
        System.out.println(output.toString());
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在整数数组中找到最长连续序列的长度的程序的时间复杂度是多少? - What is the time-complexity of a program that finds the length of the longest consecutive sequence in an array of integers? 从给定的未排序整数数组中查找最长连续元素序列的长度 - Find the length of the longest consecutive elements sequence from a given unsorted array of integers 如何从Java中的数组中提取最长的连续整数序列? - How to extract longest consecutive sequence of integers from array in Java? Java - 查找最长递增连续元素序列的程序(逻辑错误) - Java - Program to find longest increasing sequence of consecutive elements (logical errors) [java]最长连续整数序列,调试 - [java]Longest consecutive integers sequence, debug 优化此解决方案:最长连续的不同整数序列 - Optimizing this solution: Longest consecutive distinct sequence of integers 如何找到连续自然继承者的最长序列? - How to find the longest sequence of consecutive natural successors? 查找没有连续重复字符的最长子字符串的长度 - Find the length of the longest substring with no consecutive repeating characters 编写一个不使用数组查找第二长单词的程序 - Write a program to find the second longest word without using array 在Java中递归地找到数组中最长的递增序列 - recursively find the longest increasing sequence in array in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM