There are two sorted arrays nums1 and nums2 of size m and n respectively.Find the
median of the two sorted arrays. The overall run time complexity should be O(log
(m+n)).
classSolution { public: intfindKthNumber(vector<int>& nums1, vector<int>& nums2, int k){ int m = nums1.size(); int n = nums2.size(); int idx1 = 0, idx2 = 0; while (true) { if (idx1 == m) { return nums2[idx2 + k - 1]; } if (idx2 == n) { return nums1[idx1 + k - 1]; } if (k == 1) { returnmin(nums1[idx1], nums2[idx2]); }
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6
classSolution { structstate { int lsum, rsum, isum, msum; state(int l, int r, int i, int m) : lsum(l), rsum(r), isum(i), msum(m) {}; state(state& l, state& r) { lsum = max(l.lsum, l.isum + r.lsum); rsum = max(r.rsum, r.isum + l.rsum); isum = l.isum + r.isum; msum = max(max(l.msum, r.msum), l.rsum + r.lsum); } };
public: state getMaxSub(vector<int>& nums, int l, int r){ if (l == r) returnstate(nums[l], nums[l], nums[l], nums[l]); int m = (l + r) / 2; state sl = getMaxSub(nums, l, m); state sr = getMaxSub(nums, m+1, r); returnstate(sl, sr); }