Array list and finding the longest subsequence with the same number [closed]

女生的网名这么多〃 提交于 2019-12-01 14:48:01

You could use a 2d ArrayList, declared like this:

ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

and then declare the 2 ArrayLists to be added to it at the end of the process:

ArrayList<Integer> length = new ArrayList<Integer>();

ArrayList<Integer> value = new ArrayList<Integer>();

Then

1) iterate through the list checking if the element is the same as previous.

If it is, carry on until end or an element is discovered which differs, at which point store the number of the previous equal elements in the ArrayList called 'length' and the value of the element in the one called 'value'. Have an int (called index say) which stores the index of the element in length containing the length of the longest current subsequence (which will be the same as the index of the element containing the value of the element it's made up of (which has been stored in value)).

If it's not, move to the next element.

2) Repeat the process, updating index if necessary (i.e. if a longer subsequence is discovered).

To add length and value to result at the end, just do result.add(length); and result.add(value);

If you want to return one object that holds all the required info, you could wrap the int 'index' in an Integer and add it to the end of the ArrayList called 'length' or even put it in a new ArrayList and add that ArrayList to result.

Note that to retrieve an element at index i in the first ArrayList (in this case the one called 'length') after it has been stored in result, you would need to do

result.get(0).get(i);

EDIT:

So the for loop part I had in mind would be this:

boolean same = false;
int sequenceLength = 0;
Integer sequenceInteger = null; 

for (int i = 1; i < numbers.size(); i++)
        { 
            if(numbers.get(i).equals(numbers.get(i-1)))
                {
                      same = true;
                      sequenceLength++;
                }      
            else(if same == true)
                {
                      sequenceInteger = new Integer(sequenceLength);
                      //add sequenceInteger to length and numbers.get(i-1) to value 
                      same = false;
                      sequenceLength = 0;
                }
            // else do nothing since same is false, which means that the current
            // element is different from the previous and the previous is 
            // different the one before that, so there are no new values to store
        }
// end of list reached
(if same == true)
{
      sequenceInteger = new Integer(sequenceLength);
      //add sequenceInteger to length and numbers.get(i-1) to value 
      same = false;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!