数组中有多少个降序序列

时间:2015-01-31 18:26:03

标签: java arrays

我的方法应该返回数组中降序序列的数量。如果数组中的下一个数字大于前一个数字,则它是新序列的开始。有人可以指导/解释我的代码有什么问题吗?

public static int countDescents(int[] xs) {

      int descents = 0;
      int i = 0;
      for(i = 0; i < xs.length; i++)
      {
          for (int j = 0; j <= i; j++)
            descents++;

      }
    return descents;
  }

1 个答案:

答案 0 :(得分:0)

试试这段代码吧:

public static int countDescents(int[] xs) {

  int descents = 0;
  boolean onAscendingSequence = true
  int i = 0;

  // we traverse the list, from the second element
  for(i = 1; i < xs.length; i++) {
      // ascending sequence TO descending sequence
      if (onAscendingSequence && xs[i] < xs[i-1]) {
        descents++;
        onAscendingSequence = false;

      // descending sequence TO ascending sequence
      } else if (!onAscendingSequence && xs[i] > xs[i-1]) {
        onAscendingSequence = true;
      }

  }
  return descents;
}