玩转面试之高频算法题 - find max and min

描述:通过最少的比较次数(1.5n),找到数组中最大的数和最小的数

思路1:每次取出两个数比较大小,较大者和最大值比得到最大值,较小者和最小值比得到最小值

/*
use  least (1.5n) times compare to find the max and min value of an array
 */
public class FndMaxAndMin {
    public class MaxAndMin {
        int max;
        int min;
        MaxAndMin(int m, int n) {
            max = m;
            min = n;
        }
    }

    MaxAndMin findMaxAndMin(int[] nums) {
        int max = -1;
        int min = -1;
        int length = nums.length;
        if (length == 0) {
            return new MaxAndMin(max, min);
        }
        max = nums[0];
        min = nums[0];
        for (int i = 1; i < length / 2; i++) {
            int tmpMax = nums[i] > nums[length - i] ? nums[i] : nums[length - i];
            max = max > tmpMax ? max : tmpMax;
            min = min < nums[i] + nums[length - i] - tmpMax ? min : nums[i] + nums[length - i] - tmpMax;
        }
        return new MaxAndMin(max, min);
    }
}

你可能感兴趣的:(玩转面试之高频算法题 - find max and min)