Binary Search - Hard Level - Question 1
Leetcode 410 Split Array Largest Sum
Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these m subarrays.
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 10^6
1 <= m <= min(50, nums.length)
Analysis:
This question seems not to be related with binary search, actually it does!
The key argument is: if there is a value, say X, is the minimum of the largest sum among these m non-empty subarrays. Then all the values below X cannot divide the array into m non-empty subarrays (should be larger than m).
Why?
We can proof it by contradiction: if a value smaller than X, say Y, can be the minimum of the largest sum among these m non-empty subarrays, then X is NOT the minimum as claimed in the first sentence. Thus, there is no such Y existed.
If all the values smaller than X cannot be the minimum, this question become a typical binary-search problem.
We can make a guessed value, mid, first. Then we need to divide the array into m non-empty subarrays, and the sum of the each should be <= mid. If there are more subarrays, meaning mid is too smaller, we can remove all the values <= mid out of consideration; otherwise, we can consider a smaller value than mid, to see whether it is still valid, by removing all the values > mid out of consideration.
In addition, the minimum value cannot be smaller than the largest element, since the largest sum of the any non-empty subarray must be >= the largest element. So the largest element gives the left boundary of the binary search.
See the code below:
class Solution {
public:
int splitArray(vector<int>& nums, int m) {
int left = 0, right = INT_MAX;
for(auto &a : nums) left = max(a, left);
while(left < right) {
int mid = left + (right - left) / 2;
if(!isValid(nums, m, mid)) left = mid + 1;
else right = mid;
}
return left;
}
private:
bool isValid(vector<int>& nums, int& m, int mid) {
int ct = 0, sum = 0;
for(auto &a : nums) {
sum += a;
if(sum >= mid) {
++ct;
if(sum > mid) sum = a;
else sum = 0;
}
}
if(sum > 0) ++ct;
return ct <= m;
}
};
Question 2
Leetcode 4 Median of Two Sorted Arrays
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-10^6 <= nums1[i], nums2[i] <= 10^6
Analysis:
One way to think about this question is to find the Kth element of the two SORTED arrays.
We can apply binary search for this: first to make a guess of the value, mid; then count how many elements smaller than mid; if the count < k (the Kth element), we need to make the mid larger (or all the values smaller than mid are NOT valid neither); otherwise, we can test even smaller values (or shrinking the search range to the smaller half range).
For counting, we can use the binary search again, since the array is sorted.
Please see the code below:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size(), len2 = nums2.size(), sum = len1 + len2;
if(sum & 1) return findKth(nums1, nums2, sum/2+1)*1.0;
return (findKth(nums1, nums2, sum/2) + findKth(nums1, nums2, sum/2 + 1))/ 2.0;
}
private:
int findKth(vector<int> &v1, vector<int> &v2, int k) {
if(v1.empty()) return v2[k-1];
if(v2.empty()) return v1[k-1];
int left = min(v1[0], v2[0]), right = max(v1.back(), v2.back());
while(left < right) {
int mid = left + (right - left) / 2;
int ct = 0;
auto id1 = upper_bound(v1.begin(), v1.end(), mid) - v1.begin();
auto id2 = upper_bound(v2.begin(), v2.end(), mid) - v2.begin();
ct += id1 + id2;
if(ct < k) left = mid + 1;
else right = mid;
}
return left;
}
};
The time complexity is O(log(Max-Min) * (log(m) + log(n))) ~ O(log(m*n)), which may be larger than O(log(m+n)), but they are very close (remember, them are log!).
This method can be easy to extend to n (>2) sorted arrays to find the median.
A popular way to reach the literally time complexity of O(log(m+n)) is given below, if interested to check.
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size(), total = m + n;
if(total%2==0) return (help(nums1, 0, nums2, 0, total/2) + help(nums1, 0, nums2, 0, total/2+1))/2.0;
return help(nums1, 0, nums2, 0, total/2+1)/1.0;
}
private:
double help(vector<int>& n1, int st1, vector<int>& n2, int st2, int k){
int m = n1.size() - st1, n = n2.size() - st2;
if(m > n) return help(n2, st2, n1, st1, k);
if(m==0) return n2[st2+k-1];
if(k==1) return min(n1[st1], n2[st2]);
int a = min(m, k/2), b = k - a;
if(n1[st1+a-1] == n2[st2+b-1]) return n1[st1+a-1];
if(n1[st1+a-1] > n2[st2+b-1]) return help(n1, st1, n2, st2+b, k-b);
return help(n1, st1+a, n2, st2, k-a);
}
};
Comments
Post a Comment