【JAVA】Arrays.binarySearch(nums, target)

内置二分查找函数:Arrays.binarySearch(nums, target)

形式一:

  • binarySearch(Object[], Object key)

  • 参数:

    • 方法的object[]参数是要查找的数组,key参数为要查找的key值。
  • 方法的返回值有几种:

    • 1、找到的情况下:如果key在数组中,则返回搜索值的索引。
    • 2、找不到的情况下:
      • [1] 搜索值不是数组元素,且在数组范围内,从1开始计数,得“ - 插入点索引值”;
          - [2] 搜索值是数组元素,从0开始计数,得搜索值的索引值;
          - [3] 搜索值不是数组元素,且大于数组内元素,索引值为 – (length + 1);
          - [4] 搜索值不是数组元素,且小于数组内元素,索引值为 – 1。

形式二:

  • binarySearch(Object[], int fromIndex, int toIndex, Object key)

  • 参数

    • 方法的object[]参数为要查找的数组,
    • fromindex参数为开始索引(包括),toindex为结束索引(不包括),两个参数之间为查找的范围。
    • key为要查找的key。
  • 方法的返回值有几种:

    • 1.找到的情况下:如果key在数组中,则返回搜索值的索引。
    • 2.找不到的情况下:
      • [1] 该搜索键在范围内,但不是数组元素,由1开始计数,得“ - 插入点索引值”;
      • [2] 该搜索键在范围内,且是数组元素,由0开始计数,得搜索值的索引值;
      • [3] 该搜索键不在范围内,且小于范围(数组)内元素,返回–(fromIndex + 1);
      • [4] 该搜索键不在范围内,且大于范围(数组)内元素,返回 –(toIndex + 1)。

返回值:

  • int a = Arrays.binarySearch(nums, target);
  • if(a<0) a = - a - 1;
  • return a;

END

猜你喜欢

转载自www.cnblogs.com/anliux/p/12285626.html