【问题标题】:Write a program that takes an array/arraylist of integer and finds longest sub array/arraylist whose entries are equal [closed]编写一个程序,该程序采用整数数组/数组列表并找到条目相等的最长子数组/数组列表 [关闭]
【发布时间】:2017-05-16 21:16:23
【问题描述】:

我正在尝试解决一本书中的一个问题。我在 Java 编程面试元素一书中发现了这个问题。

解决方案: 例如,如果 arraylist = [1, 2, 2, 0, 0, 0, 1, 1, 1, 1] 输出必须是 = [1, 1, 1, 1, 1]

我的代码不起作用:

public class SubArraySameEntry {

 public static int subArr(List<Integer> arr) {



      int count = 1;
      int e=0;

      for (int i = 1; i < arr.size(); i++) {
           int m = 0;

           if (arr.get(i - 1).equals(i)) {
                count++ ;
           }
           if (count > m) {
                m = count;
                e = arr.get(i);
           }
           if (!arr.get(i - 1).equals(i)) count =1;

      }

      return count;
 }

 public static void main(String[] args) {
      List<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 2, 0, 0, 0, 1, 1, 1, 1));
      System.out.println(arr.toString());
      int newArr = subArr(arr);
      for (int i = 0; i < newArr; i++) {
           System.out.print(arr.get(i) + " ");

      }
 }
}

我尝试并花费了太多时间但无法解决。

【问题讨论】:

  • 你能解释一下输出吗?我会从问题的标题中预料到[1,2,3,4],因为这是具有相等连续数字的子数组的最大长度。为什么应该是[1,1,1,1,1]
  • 标题说要查找最长子数组的长度,但示例返回子数组本身。
  • @Tunaki 我预计返回是4,因为这是最长子数组的长度。
  • 最快的解决方案(无排序):构建elementcount 的映射。查找/记住element 最高的count。构建结果为countelement 副本。
  • 只是为了好玩:Map&lt;Integer, Long&gt; collect = arr.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); collect.entrySet().stream().max((e1, e2) -&gt; e1.getValue().compareTo(e2.getValue())).ifPresent(v -&gt; System.out.println("Value " + v.getKey() + " exists " + v.getValue() + " times.")) -> 输出“值 1 存在 5 次。”。然后循环打印 1 五次。

标签: java arrays algorithm arraylist


【解决方案1】:

关于您的代码,排序 (Collections.sort(arr);) 将完全阻止您找到解决方案。

我会在伪代码方面提供帮助

Given a counter c
A max counter m
A variable for the max element, e
And an array a
For every element in the array a
    If the element matches the previous element
        increment the count c, and:
          if the count c > m:
            set m to c, and e to the current value
    If it doesn't match the previous, reset the count to 1

Then after all this, the result is e, c times

【讨论】:

  • 您是否查看了指定的“解决方案”(问题的第 2 段)?据此,“子数组”不是由连续的相等值构建的,只是相等的值,即输入有五个 1 但只有四个在一起,但答案仍然是五个 1。因此,如果您先调用 sort(),您的代码只会得到正确的结果。
  • @weston 我需要帮助来解决它。但是感谢算法
  • 你说得对,这很简单,但你这样做是为了练习,所以有人为你做这件事有什么意义。
  • 我不知道你为什么认为我的反应很糟糕,或者我个人认为我不是,我正在努力提供帮助。所以你对我的算法的解释的主要错误是m需要在循环外定义,arr.get(i - 1).equals(i)需要arr.get(i - 1).equals(arr.get(i))ideone.com/8paHKC
  • 抱歉,我们中的一些人认为问题是针对“连续子数组”,您可以先排序,然后这样就可以了,但我不知道是否有更好的方法(可能是)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
相关资源
最近更新 更多