判斷是否valid只要搜尋整個陣列,pair by pair如果找到比當前搜尋的差還小或相等,而且滿足目標對數(pairs),那就回傳true,否則就代表這個差太小了,要往更大的找
Code
第一次寫的思路幾乎一樣,但在判斷valid的條件時有點小bug,忘了用到diff
classSolution{publicintminimizeMax(int[] nums,int p){if(p ==0)return0;Arrays.sort(nums);int l =0, r =(int)Math.pow(10,9);int res =(int)Math.pow(10,9);while(l <= r){int mid = l +(r - l)/2;if(isValid(nums, p, mid)){
res = mid;
r = mid -1;// Search for smaller diff.}else{
l = mid +1;// Try for bigger diff}}return res;}privatebooleanisValid(int[] nums,int p,int diff){int i =0, count =0;// Go through nums, pair by pairwhile(i < nums.length -1){// Found valid pairif(Math.abs(nums[i]- nums[i +1])<= diff){++count;
i +=2;// Move to another pair}else{++i;// In case the second number could be in the next pair}// Found enough pairif(count == p)returntrue;}returnfalse;}}
▶
Failed Attempt
classSolution{int res =0;publicintminimizeMax(int[] nums,int p){int smallest =Integer.MAX_VALUE, secSmallest =0, largest =Integer.MIN_VALUE;// Find smallest and largest numfor(int num : nums){
smallest =Math.min(smallest, num);
largest =Math.max(largest, num);}// Find the second smallest numfor(int num : nums){if(num == smallest)continue;
secSmallest =Math.min(secSmallest, num);}// Define upper bound and lower boundint l = secSmallest - smallest, r = largest;Arrays.sort(nums);// Start binary searchwhile(l <= r){int mid = l +(r - l)/2;// Valid, so check even smaller diffif(isValid(nums, p, mid)>=0){
r = mid -1;}else{
l = mid +1;}}return res;}privateintisValid(int[] nums,int p,int diff){int max =-1;for(int i =0, pCounter =0; i < nums.length && pCounter < p; i +=2, pCounter++){
max =Math.max(max,Math.abs(nums[i]- nums[i +1]));}if(max >-1){
res =Math.max(res, max);}return max;}}