Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有更好的方法来编写此代码?(查找数组中的最小数和最大数)[Java]_Java_Arrays_Algorithm_Search - Fatal编程技术网

有没有更好的方法来编写此代码?(查找数组中的最小数和最大数)[Java]

有没有更好的方法来编写此代码?(查找数组中的最小数和最大数)[Java],java,arrays,algorithm,search,Java,Arrays,Algorithm,Search,所以我有一段代码,它基本上是试图找到数组中最大的数字和最小的数字,这就是票价。但我发现自己在写两个for循环,我想知道是否有更有效的方法来写这个 /** Setting cheapestCost to the index of the cheapest transport obj*/ for(int i = 0; i < 15; i++) { if(allTransports[cheapestCost].getTicketPrice() > allTr

所以我有一段代码,它基本上是试图找到数组中最大的数字和最小的数字,这就是票价。但我发现自己在写两个for循环,我想知道是否有更有效的方法来写这个

    /** Setting cheapestCost to the index of the cheapest transport obj*/
    for(int i = 0; i < 15; i++) {
        if(allTransports[cheapestCost].getTicketPrice() > allTransports[i].getTicketPrice()) {
            cheapestCost = i;
        }
    }
        
    /** Setting greatestCost to the index of the most expensive transport obj*/
    for(int i = 0; i < 15; i++) {
        if(allTransports[greatestCost].getTicketPrice() < allTransports[i].getTicketPrice()) {
            greatestCost = i;
        }
    }

谢谢

在我看来,您可以将这两个循环组合起来:

for(int i = 0; i < 15; i++) {
    int price = allTransports[i].getTicketPrice();

    if(allTransports[cheapestCost].getTicketPrice() > price) {
        cheapestCost = i;
    }

    if(allTransports[greatestCost].getTicketPrice() < price) {
        greatestCost = i;
    }
}
    

为什么不使用数组排序

Int[] Tickets = new int[TicketsPrice.length]
For(int i =0;i < Tickets.length ; i++){
Tickets[i] = TicketsPrice.getPrice();
}
Int[] Arr = Arrays.sort(Tickets)
Arr[0] \\ => smallest number
Arr[Arr.length -1] \\=> largest number 

有一个技巧可以减少你必须进行的比较。将数组分成几对,并在每对中进行比较。这对中较高的数字是最高元素的候选值,因此在那里进行比较。这对中较低的数字是最低元素的候选,因此在那里进行比较。这需要每两个数字进行三次比较,而简单的方法需要每两个数字进行两次比较或每两个数字进行四次比较。

是否更好取决于品味。您可以使用流操作:

    /** Setting cheapestCost to the index of the cheapest transport obj*/
    int cheapestCost = IntStream.range(0, 15)
            .boxed()
            .min(Comparator.comparing(i -> allTransports[i].getTicketPrice()))
            .orElseThrow();

类似地,对于最昂贵的运输票,只需使用max而不是min。一种简单的方法是,您应该按票价升序排序数组,然后获得第一个和最后一个元素。 但不要更改数组的原始顺序,只需将排序后的数组存储在新变量中即可

Transport[] allTransports = {new Transport(), new Transport()};
List<Integer> naturalSortedPrices =
Arrays.stream(allTransports).map(Transport::getTicketPrice).sorted()
        .collect(Collectors.toList());

int cheapestCost = naturalSortedPrices.get(0);
int greatestCost = naturalSortedPrices.get(naturalSortedPrices.size() - 1);

为什么不在同一个循环中执行两个操作?两个循环在同一范围内迭代,两个操作彼此不交互,因此没有任何东西可以阻止将两个循环合并为一个循环。