【问题标题】:Find smaller or equal to X from duplicated sorted list从重复的排序列表中查找小于或等于 X
【发布时间】:2015-08-22 21:47:02
【问题描述】:

给定一个数组列表并排序

ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(4);
list1.add(15);
list1.add(16);
list1.add(3);
list1.add(3);
list1.add(8);
System.out.println(list1); // [1, 4, 15, 16, 3, 3, 8]
Collections.sort(list1,3);
System.out.println(list1); // [1, 3, 3, 4, 8, 15, 16]

To find larger 或在已排序的重复列表中相等,例如“3”

int index = Collections.binarySearch(list1, 3);
ArrayList<Integer> list2 = new ArrayList<> (list1.subList(index < 0 ? - index - 1 : index, list1.size()));    

这给了我们

[3,3,4,8,15,16]

但是对于较小或相等的情况如何做到这一点?这是我尝试过的。

ArrayList<Integer> list3 = new ArrayList<> (list1.subList(0, index < 0 ? - index - 1 : index + 1));

哪个输出

[1, 3]

预期输出

[1, 3, 3]

【问题讨论】:

  • 您的意思是要查找所有大于某个数字的重复项? (在您的示例中为 3)
  • @OferYuval,我的错,它应该小于或等于 3。
  • 在将数字添加到列表时,您可以进行排序并查找重复项吗?还是在将所有数字都添加到列表后需要列表?

标签: java sorting arraylist


【解决方案1】:

您可以使用https://docs.oracle.com/javase/8/docs/api/java/util/List.htmlindexOflastIndexOf 方法。一个例子

    List<Integer> list1 = new ArrayList<>();
    list1.add(1);
    list1.add(4);
    list1.add(15);
    list1.add(16);
    list1.add(3);
    list1.add(3);
    list1.add(8);

    System.out.println(list1); // [1, 4, 15, 16, 3, 3, 8]
    Collections.sort(list1);
    System.out.println(list1); // [1, 3, 3, 4, 8, 15, 16]

    //For equals or larger than 3
    int index = list1.indexOf(3);
    List<Integer> list2 = index > -1 ? list1.subList(index, list1.size()) : new ArrayList<>();
    System.out.println(list2); // [3, 3, 4, 8, 15, 16]

    //For equals or smaller than 3
    index = list1.lastIndexOf(3);
    List<Integer> list3 = index > -1 ? list1.subList(0, index + 1) : new ArrayList<>();
    System.out.println(list3); // [1, 3, 3]

【讨论】:

  • 另一个建议是使用速记方法:ArrayList&lt;Integer&gt; list3 = new ArrayList&lt;&gt; (list1.subList(0, index &lt; 0 ? - index - 1 : list1.lastIndexOf(list1.get(index)) + 1));。但是,这个答案是不可读的。
  • 更新了答案,检查列表中是否缺少预期的 X。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2011-01-25
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多