Java在arraylist中查找值

我在arraylist中添加了一些数字。 我想从它找到一定的值。例如我有4,4,9,9,18。 我想找到26的值。如果列表中26>最大值它将显示18,如果值为17,它将显示9,如果值为5,它将显示4.还有另一种方法来实现这个搜索,因为class轮搜索可能会很慢。

search value 26 [4,4,9,9,18] display 18 [20,20,29,29,4] display 20 [28,28,28,1,10] display 28 

如果你有这个列表并搜索26,它将输出第一个元素。 因为第一个元素<=比搜索的值。

但目前的输出是

价值2:9

  public class Arraylist { public static ArrayList aList; public static void main(String[] args) { aList = new ArrayList(); aList.add(4); aList.add(4); aList.add(9); aList.add(9); aList.add(18); int value = 26; int value2 = 0; for (int i = 0; i < aList.size(); i++) { if (aList.get(i) <= value) { if (i + 1  aList.size()) { value2 = aList.get(i); } } } System.out.println("Value of value2 : " + value2); } } 

我用数组编写了代码。 您可以轻松地将其应用于ArrayList

 int a[] = {28,28,28,1,10}; // int a[] = {20,20,29,29,4}; // other input of yours // int a[] = {4,4,9,9,18}; int x = 26; int liVal = -1; for(int i=0; i x { if(liVal==-1) // if we could not find any largest value smaller than x liVal = a[i]; // return the value > x break; } else if(x > a[i]) // find the largest value smaller than x, { if(liVal < a[i]) liVal = a[i]; } System.out.println(liVal); 

一个简单且未经优化的版本:

 int value = 26 // or whatever parameter you get int retVal = Integer.MIN_VALUE; for (int i : list) { if (i <= value && i > retVal) { retVal = i; } } return retVal; 

如果数组已排序,您可以使用二进制搜索的变体。
见http://en.wikipedia.org/wiki/Binary_search_algorithm

对列表进行排序后, Collections binarySearch将执行以下操作:

 Collections.sort(aList) int index = Collections.binarySearch(aList) 

如果index是非负的,则在列表中找到该数字, index是位置。 如果它是否定的,则找不到它,但index指示它在列表中的位置。

并使用O(log n)运行时进行搜索。

如果我理解正确,您希望在数组中找到小于或等于value的最大数字。 我会这样做:

 for (int i = 0; i < aList.size(); i++) { if ( aList.get(i) <= value && aList.get(i) > value2) { value2 = aList.get(i); } } 

同样在您的示例中,您执行value2 = 0 。 如果您可以确保数组仅包含正值,则可以。 否则,最好使用value2 = Integer.MIN_VALUE

最后,此代码假定数组不保证排序,您只需要搜索一次。 否则, 二进制搜索可能更具性能。 关于这个问题的其他答案已经说明了如何实现这一点。

根据OP的评论:

  1. 列表未排序
  2. if value
  3. if value> max return max
  4. 如果min <= value <= max,则返回最接近的val <= value

     public static int findValue(List list, int value){ int min = Integer.MAX_VALUE, nearest = Integer.MIN_VALUE; for(Integer v : list){ if(v == value) return value; if(v > nearest && v < value) nearest = v; if(v < min) min = v; } return value < min ? min : nearest; } 

作为旁注,您不需要跟踪最大值,因为如果值> max(list),则nearest = max。