O(n) without branch prediction
interface HighLow { static int[] findLargestAndSmallest(int[] nums) { // assert nums.length >= 0; if (nums == null || nums.length < 1) return null; java.util.function.Function<Boolean, Integer> f = a -> java.util.Arrays.stream(nums).reduce((x,y) -> x + ((a?(x-y):(y-x)) >>31) * (x-y)).getAsInt(); // actually returning SmallestAndLargest return new int[] {f.apply(false), f.apply(true)}; } }
- interface HighLow {
static int[] findLargestAndSmallest(int[] nums) {// Change min and max below to be the highest and lowest values// in the nums array provided to the functionif(nums == null || nums.length == 0) return null;int min = nums[0];int max = nums[0];for(int n : nums) {if(n < min) {min = n;} else if(n > max) {max = n;}}return new int[]{min, max};}- static int[] findLargestAndSmallest(int[] nums) {
- // assert nums.length >= 0;
- if (nums == null || nums.length < 1) return null;
- java.util.function.Function<Boolean, Integer> f = a -> java.util.Arrays.stream(nums).reduce((x,y) -> x + ((a?(x-y):(y-x)) >>31) * (x-y)).getAsInt();
- // actually returning SmallestAndLargest
- return new int[] {f.apply(false), f.apply(true)};
- }
- }