double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
if(m > n) return findMedianSortedArrays(nums2, nums1);
nums1.insert(nums1.begin(), INT_MIN);
nums2.insert(nums2.begin(), INT_MIN);
nums1.push_back(INT_MAX);
nums2.push_back(INT_MAX);
m = nums1.size();
n = nums2.size();
int il = 0, ih = m-1;
int i, j;
while(il<=ih) {
i = (il + ih)/2;
j = (m+n+1)/2 - i;
if(nums1[i-1]>nums2[j]) {
ih = i-1;
}
else if(nums2[j-1]>nums1[i]) {
il = i+1;
}
else break;
}
if((m+n)%2==0) return (max(nums1[i-1],nums2[j-1]) + min(nums1[i],nums2[j]))/2.;
return max(nums1[i-1], nums2[j-1]);
}
Friday, August 3, 2018
Friday, January 5, 2018
740. Delete and Earn
https://leetcode.com/problems/delete-and-earn/description/
int deleteAndEarn(vector<int>& nums) {
vector<int> ns(100001, 0);
for(int i: nums) ns[i]++;
int skip = 0, keep = 0;
for(int i=1; i<ns.size(); i++) {
int keepi = skip + i * ns[i];
skip = max(keep, skip);
keep = keepi;
}
return max(keep, skip);
}
int deleteAndEarn(vector<int>& nums) {
vector<int> ns(100001, 0);
for(int i: nums) ns[i]++;
int skip = 0, keep = 0;
for(int i=1; i<ns.size(); i++) {
int keepi = skip + i * ns[i];
skip = max(keep, skip);
keep = keepi;
}
return max(keep, skip);
}
Thursday, January 4, 2018
516. Longest Palindromic Subsequence
https://leetcode.com/problems/longest-palindromic-subsequence/description/
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int> (n, 0));
for(int j=0; j<n; j++) {
dp[j][j] = 1;
for(int i=j-1; i>=0; i--) {
if(s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2;
else dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
return dp[0][n-1];
}
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int> (n, 0));
for(int j=0; j<n; j++) {
dp[j][j] = 1;
for(int i=j-1; i>=0; i--) {
if(s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2;
else dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
return dp[0][n-1];
}
Subscribe to:
Posts (Atom)