【问题标题】:Find longest squential streak in arraylist java [closed]在arraylist java中查找最长的连续条纹[关闭]
【发布时间】:2020-06-02 12:09:29
【问题描述】:

我正在尝试在 java 中编写代码,假设我有一个数组列表 (1,3,4,5,8,9,11,12,13,14,15)

我需要代码来分析数组列表中最长的连续数字。从上面的数组列表中,11,12,13,14,15 是最长的连续,所以代码应该在输出中以另一个数组列表的形式给出这个。

代码应该在任何由不同数字组成的 ArrayList 上执行

实际上,我已经编写了从更大的数组列表中提取正值索引并将其存储在另一个数组列表中的代码。现在,我一直在寻找新创建的数组列表中最长的连续数字。

这是我的代码:

List<Integer> mega = new ArrayList<Integer>();
for (int i = 0; i <= data.size() - 1; i++) {
    double a = (data.get(i).adjClose) - (data.get(i).open); //calculating a value
    if (a > 0) { // if value is bigger than zero, then store the index of that element in a new arraylist
        mega.add(i);
    }
}    

【问题讨论】:

  • 分享你目前尝试过的代码。
  • 请编辑您的问题,并发布格式化的代码。见how to ask a good question
  • 您使用的是整数还是十进制值?为什么要访问同一个对象的不同属性,这与顺序值有什么关系?

标签: java arraylist


【解决方案1】:
ArrayList<Integer> bigger = new ArrayList<>();
for (int x = 0; x < numbers.size(); x++) {
  int current = numbers.get(x);
  ArrayList<Integer> temp = new ArrayList<>();
  temp.add(current);
  for (int y = x + 1; y < numbers.size(); y++) {
    int nextValue = numbers.get(y);
    if (nextValue == current + 1) {
      temp.add(nextValue);
      current = nextValue;
    }
    else {
      break;
    }
  }

  if (temp.size() > bigger.size()) {
    bigger.clear();
    bigger.addAll(temp);
  }
}

numbers 是您的号码的 ArraList,并且 bigger 里面是你的序列。

【讨论】:

  • 谢谢。上面的代码有帮助。
猜你喜欢
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
相关资源
最近更新 更多