leetcode 4. Median of Two Sorted Arrays
来源:互联网 发布:台达触摸屏编程视频 编辑:程序博客网 时间:2024/06/05 23:23
这个题目我的思路是从两个数组的开始位置向后找第(nums1.size()+nums2.size())/2和第(nums1.size()+nums2.size()-1)/2大的元素,如果总元素个数是奇数返回第(nums1.size()+nums2.size())/2大的元素即可,否则求一个均值。
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int length=nums1.size()+nums2.size(); int value; if(length%2==1) { int i=0,j=0,k=0; for(;i<nums1.size() && j<nums2.size() && k<=length/2 ;k++ ) { if(nums1[i]<nums2[j]) { value=nums1[i];i++; } else { value=nums2[j]; j++; } } for(;i<nums1.size() && k<=length/2; i++,k++) value=nums1[i]; for(;j<nums2.size() && k<=length/2;j++,k++) value=nums2[j]; return value; }else{ int i=0,j=0,k=0,l=0; int m,n; for(;i<nums1.size() && j<nums2.size() && k<=length/2 ;k++,l++) { if(nums1[i]<nums2[j]) { if(k==length/2) m=nums1[i]; if(l==(length-1)/2) n=nums1[i]; i++ ; } else { if(k==length/2) m=nums2[j]; if(l==(length-1)/2) n=nums2[j]; j++; } } for(;i<nums1.size() && k<=length/2; i++,k++,l++) { if(k==length/2) m=nums1[i]; if(l==(length-1)/2) n=nums1[i]; } for(;j<nums2.size() && k<=length/2;j++,k++,l++) { if(k==length/2) m=nums2[j]; if(l==(length-1)/2) n=nums2[j]; } return (m+n)/2.000; } }};
阅读全文
0 0
- [LeetCode]4.Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- LeetCode --- 4. Median of Two Sorted Arrays
- [Leetcode] 4. Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 【leetcode】4. Median of Two Sorted Arrays
- Leetcode-4.Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- [leetcode]4. Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- [LeetCode]4. Median of Two Sorted Arrays
- leetCode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- Project configuration is not up-to-date with pom.xml. Run Maven->Update Project or use Quick Fix
- mongo学习之二
- windows下安装mongoDB以及配置启动
- centos中Tomcat的安装
- MyEclipse下maven 命令后控制台无输出
- leetcode 4. Median of Two Sorted Arrays
- Android Material Design ToolBar 使用
- mybatis的日期查询与字段的模糊查询例子
- KMP算法之java实现
- [Tomcat]idea安装使用最新版Tomcat
- Weex入门教程
- ndk-build编译64位.so,出现ndk error: cast from 'int*' to 'int' loses precision [-fpermissive]
- iOS(OC)—仿支付宝我的二维码页面系统亮度调整
- 718