Ad
Code
Diff
  • interface HighLow {
    
        static int[] findLargestAndSmallest(int[] nums) {
            if (isCollectionEmpty(nums))
                return null;
            else if (hasOneElement(nums))
                return new int[]{nums[0], nums[0]};
            else if (hasTwoElements(nums))
                return sortTwoElements(nums);
    
            return findLargestAndSmallestGeneric(nums);
        }
    
        private static int[] findLargestAndSmallestGeneric(int[] nums) {
            int max = Integer.MIN_VALUE;
            int min = Integer.MAX_VALUE;
    
            for (int num : nums) {
                if (max < num)
                    max = num;
                if (min > num)
                    min = num;
            }
    
            return new int[]{min, max};
        }
    
        static boolean hasOneElement(int[] nums) {
            return nums.length == 1;
        }
    
        static boolean hasTwoElements(int[] nums) {
            return nums.length == 2;
        }
    
        private static int[] sortTwoElements(int[] nums) {
            return (nums[0] <= nums[1])
                    ? new int[]{nums[0], nums[1]}
                    : new int[]{nums[1], nums[0]};
        }
    
        private static boolean isCollectionEmpty(int[] nums) {
            return nums == null || nums.length == 0;
        }
    }
    • interface HighLow {
    • static int[] findLargestAndSmallest(int[] nums) {
    • if (isCollectionEmpty(nums))
    • return null;
    • else if (hasOneElement(nums))
    • return new int[]{nums[0], nums[0]};
    • else if (hasTwoElements(nums))
    • return sortTwoElements(nums);
    • return findLargestAndSmallestGeneric(nums);
    • }
    • private static int[] findLargestAndSmallestGeneric(int[] nums) {
    • int max = Integer.MIN_VALUE;
    • int min = Integer.MAX_VALUE;
    • for (int num : nums) {
    • if (max < num)
    • max = num;
    • else if (min > num)
    • if (min > num)
    • min = num;
    • }
    • return new int[]{min, max};
    • }
    • static boolean hasOneElement(int[] nums) {
    • return nums.length == 1;
    • }
    • static boolean hasTwoElements(int[] nums) {
    • return nums.length == 2;
    • }
    • private static int[] sortTwoElements(int[] nums) {
    • return (nums[0] <= nums[1])
    • ? new int[]{nums[0], nums[1]}
    • : new int[]{nums[1], nums[0]};
    • }
    • private static boolean isCollectionEmpty(int[] nums) {
    • return nums == null || nums.length == 0;
    • }
    • }