简体   繁体   中英

Removing useless elements of an array

My program is trying to find the longest contiguous sequence of an array, but the output is wrong.

public class longsec {
    public int[] longestForward(int[] arr){
        int subSeqLength = 1;
        int longest = 1;
        int indexStart = 0;
        int indexEnd = 0;

        for (int i = 0; i < arr.length - 1; i++)
        {
            if (arr[i] == arr[i + 1] - 1)
            {
                subSeqLength++;
                if (subSeqLength > longest)
                {
                    longest = subSeqLength;
                    indexStart = i + 2 - subSeqLength;
                    indexEnd = i + 2;
                }

            } 
            else
                subSeqLength = 1;
        }


       int T[] = new int[arr.length];
        for (int i = indexStart; i < indexEnd; i++)


             T[i]= arr[i];


        return T;

    }}  

input

{23,10,22,5,33,8,9,21,50,41,60,80,99, 22,23,24,25,26,27}

output

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 23, 24, 25, 26, 27]

right output

[22, 23, 24, 25, 26, 27]

What have i done wrong? Thank you.

The reason why that is happening is because you are creating an array with the same size as the array you inputted. As you can see here.

int T[] = new int[arr.length];

However if just change that piece of code you will get an arrayIndexOutOfBoundsException. And it will be thrown here:

for (int i = indexStart; i < indexEnd; i++)

         T[i]= arr[i];

Because indexStart will ussually be greater than the length of the array. So instead of looping from indexStart to indexEnd what you should be doing is looping through the length of the contiguous numbers like this.

int T[] = new int[longest];

for(int i = 0; i < longest; i++)
    T[i] = arr[i + indexStart];

That should give you your desired output. What I am doing is just offsetting the iteration by the indexStart value of your array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM