简体   繁体   English

删除数组中无用的元素

[英]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} {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] [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] [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. 但是,如果仅更改这段代码,您将获得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. 因为indexStart通常会大于数组的长度。 So instead of looping from indexStart to indexEnd what you should be doing is looping through the length of the contiguous numbers like this. 因此,与其从indexStart到indexEnd循环,不如要做的是遍历这样的连续数字的长度。

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. 我正在做的只是通过数组的indexStart值抵消迭代。

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

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