给出一个数组,返回它的最大值和最小值。

Ben has a very simple idea to make some profit: he buys something and sells it again. Of course, this wouldn't give him any profit at all if he was simply to buy and sell it at the same price. Instead, he's going to buy it for the lowest possible price and sell it at the highest.

Task

Write a function that returns both the minimum and maximum number of the given list/array.

Examples

MinMax.minMax(new int[]{1,2,3,4,5}) == {1,5}
MinMax.minMax(new int[]{2334454,5}) == {5, 2334454}
MinMax.minMax(new int[]{1}) == {1, 1}

 代码:

import java.util.Arrays;


public class MinMax {
    //方法一
    public static int[] minMax(int[] arr) {
        int[] b=new int[2];
        if(arr.length==1){
            System.arraycopy(arr,0,b,0,1);
            System.arraycopy(arr,0,b,1,1);
        }
        if(arr.length==2){
            if(arr[0]<arr[1]){
                System.arraycopy(arr,0,b,0,2);
            }else {
                System.arraycopy(arr,1,b,0,1);
                System.arraycopy(arr,0,b,1,1);
            }
        }
        if(arr.length>2){
            for(int k=0;k<arr.length-1;k++){
                for(int j=0;j<arr.length-k-1;j++){
                    if(arr[j]>arr[j+1]){
                        int t=arr[j+1];
                        arr[j+1]=arr[j];
                        arr[j]=t;
                    }
                }
            }
            System.arraycopy(arr,0,b,0,1);
            System.arraycopy(arr,arr.length-1,b,1,1);
        }
        return b;
    }
    
    //方法二
    public static int[] minMax2(int[] arr) {
        Arrays.sort(arr);
        return new int[]{arr[0],arr[arr.length-1]};
    }
    
    public static void main(String[] args) {
//        int[] b={1};
        int[] b={10,2,20,100};
        System.out.println(Arrays.toString(minMax(b)));
        System.out.println(Arrays.toString(minMax2(b)));
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43969830/article/details/89218049