java—在数组中查找数字的最佳实践是什么?

guz6ccqo  于 2021-06-30  发布在  Java
关注(0)|答案(4)|浏览(204)

…还有,这到底是怎么回事?

int [] numbers1To9 = new int[]{1,2,3,4,5,6,7,8,9};
    System.out.println("one is here, true or false?: "+Arrays.asList(numbers1To9).contains(1));

输出:这里有一个,是真还是假?:假

2hh7jdfx

2hh7jdfx1#

除了自己在int[]中查找数字之外,您还可以很容易地将int[]转换为列表:

int [] numbers1To9 = new int[]{1,2,3,4,5,6,7,8,9};
List<Integer> ilist = IntStream.of(numbers1To9).boxed().collect(Collectors.toList());
System.out.println("one is here, true or false?: "+ ilist.contains(1));

输出: one is here, true or false?: true 编辑
正如在下面的评论中提到的,如果您的唯一目标是检查值的存在,那么您根本不需要装箱和收集:

boolean contains1 = IntStream.of(numbers1To9).anyMatch(i -> i == 1);
System.out.println("one is here, true or false?: "+ contains1);
9njqaruj

9njqaruj2#

你的代码不起作用,因为 Arrays#asList 在基元类型的数组上返回 List 只有一个元素是数组本身。有很多方法可以做你想做的事。一个简单的方法如下:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] numbers1To9 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        System.out.println("one is here, true or false?: " + Arrays.stream(numbers1To9).anyMatch(n -> n == 1));
    }
}

输出:

one is here, true or false?: true
myzjeezk

myzjeezk3#

如果使用排序数组,或者对未排序数组的排序操作被认为是“廉价的”,则 binarySearch 可以认为是一个好的选择;它避免了创建更多的集合(例如 Lists )因为它直接与原始数组一起工作,其机制旨在找到存储所需密钥的位置(或其中一个位置)。因此,您可以识别它的存在(隐式)和索引所在的位置。
您已经对数组进行了排序,因此在您的情况下不需要(这是使用此算法的一个优势);请注意,在使用未排序的数组时,调用 Arrays.sortbinarySearch 是必须的,以避免“未定义”的结果。
例如,如果您想知道 1 存在:

/*Arrays.sort(numbers1To9); -- only if unsorted*/
    boolean found = (Arrays.binarySearch((numbers1To9), 1))>=0?true:false; //--> true

例如,如果您也希望获得值的位置 2 :

/*Arrays.sort(numbers1To9); -- only if unsorted*/
    int pos = Arrays.binarySearch((numbers1To9), 2); //-->1
    boolean found = pos>=0; //--> true
``` `binarySearch` 只有在找不到元素时才会返回负输出。如果要找到的密钥是重复的,则无法保证指定密钥的哪个位置将返回。
不管怎样,如果结果是 `>=0` ,数组保证包含数字,所需的值也保证存储在返回的索引中。
找不到钥匙的结果很有趣
如果找不到键,则显示的否定结果遵循以下逻辑:
(-(插入点)-1)。插入点定义为将键插入数组的点:大于键的第一个元素的索引,如果数组中的所有元素都小于指定的键,则为a.length。这保证了当且仅当找到键时,返回值将>=0。
所以如果你想找到任何大于9的数字,插入点就是 `numbers1To9.length -> 9` . 因此, `10` 以及 `INTEGER.MAX_VALUE` 将输出相同的位置:

int pos = Arrays.binarySearch((numbers1To9), 10); // -(9)-1 --> pos=-10
pos = Arrays.binarySearch((numbers1To9), Integer.MAX_VALUE); // -(9)-1 --> pos=-10

数字为0时,插入点为 `0` (因为1更大,在数组中的位置是0):

int pos = Arrays.binarySearch((numbers1To9), 0); // -(0)-1 --> pos=-1

为了了解binarysearch如何处理未排序的数组:

int [] numberUnsorted= new int[]{1,2,4,9,7,6,5,8,3};
int pos = Arrays.binarySearch((numberUnsorted), 3); //--> pos = -3 (FAIL)
pos = Arrays.binarySearch((numberUnsorted), 9); //--> pos = -10 (FAIL)
pos = Arrays.binarySearch((numberUnsorted), 6); //--> pos = -4 (FAIL)

所以称它们为“未定义的”是一个真正仁慈的想法
请注意,二进制搜索将是查找
数组中的一个数字,其条件是数组被排序。在其他情况下,如果数组未排序,您可能会意识到对其排序的复杂性,并决定另一种不需要排序操作的机制是否是更好的方法。它将取决于数组类型、大小和值。如果不知道搜索的具体上下文,通常没有“最佳定义方式”
oyt4ldly

oyt4ldly4#

在数组中查找数字的最佳方法取决于数组是否排序
如果对数组进行了排序,则可以在运行o(log(n))时找到数组中的num。
但是如果你的数组没有被排序,那么你需要考虑对数组进行排序,在有了一些算法之后,你可以在数组中找到你的数字。
比如二进制搜索等等。。。

相关问题