c++ - 两个排序数组的中位数超过时间限制的问题
问题描述
在超过时间限制的情况下解决 LeetCode 上的测验时遇到了麻烦。这两天我一直在解决这个问题,但我仍然不明白为什么它不能通过。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int leng1 = nums1.size();
int leng2 = nums2.size();
int combinedleng = leng1 + leng2;
int head = 0, tail = leng1;
int cut1, cut2;
bool found = false;
if(leng1 > leng2 && leng2 != leng1){return findMedianSortedArrays(nums2, nums1);}
while(head <= tail && !found) {
cut1 = (head + tail)/2;
cut2 = (combinedleng +1)/2 - cut1;
double L1 = (cut1 == 0) ? INT_MIN : nums1[cut1-1];
double L2 = (cut2 == 0) ? INT_MIN : nums2[cut2-1];
double R1 = (cut1 == leng1) ? INT_MAX : nums1[cut1];
double R2 = (cut2 == leng2) ? INT_MAX : nums2[cut2];
if(L1 > R2){head = cut1 -1;}
else if(L2 > R1){head = cut1 +1;}
else {
if(combinedleng %2 ==0){return (max(L1, L2) + min(R1, R2))/2;}
else{return max(L1,L2);}
}
}
return -1;
}
};
当测试用例 [3,4][1,2] 时,代码结果将是 'nums1' 必须是非递减的。
解决方案
推荐阅读
- android - WebView 地理位置仅适用于 Wifi 开启/始终扫描
- node.js - 无法在量角器中找到元素
- android - 即使有意图过滤器,我的应用程序在共享对话框中也不可见
- spring-boot - 存储库层 EntityManager 链式方法的 Mockito 测试用例
- flutter - 从资产中读取 Markdown 文本并将其加载到 Markdown() 小部件中
- c# - 使用可拖动和可调整大小的选择窗口创建自定义图片框
- elasticsearch - 弹性搜索数据上传
- node.js - 无法使用 PM2 和 NodeJS 捕获关闭信号
- python - 如何应用正则表达式来获得具有近似剩余地址匹配的确切门牌号
- excel - 如何在选择中的每个单元格周围添加文本框/形状?