we should do it in O(n).
and with Array length of 0 or null.
no one likes a crash.
import java.util.*; interface HighLow { static int[] printLargestAndSmallest(int[] nums) { int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE; for(int i=0;i<nums.length; i++){ if(max<nums[i])max=nums[i]; if(min>nums[i])min=nums[i]; } return nums == null || nums.length==0 ? null : new int[]{min, max}; } }
- import java.util.*;
- interface HighLow {
- static int[] printLargestAndSmallest(int[] nums) {
Arrays.sort(nums);return new int[] {nums[0], nums[nums.length-1]};}- int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
- for(int i=0;i<nums.length; i++){
- if(max<nums[i])max=nums[i];
- if(min>nums[i])min=nums[i];
- }
- return nums == null || nums.length==0 ? null : new int[]{min, max};
- }
- }