Median of Two Sorted Arrays(hard)
来源:互联网 发布:牛奶推荐 知乎 编辑:程序博客网 时间:2024/06/01 12:11
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)).
我的解答:
class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { vector<int> neo; double outcome=0 ; int a = nums1.size() + nums2.size(); if (a % 2 != 0) { int current = 0; int b = 0; int c = 0; while (b != nums1.size() || c != nums2.size()) { if (b == nums1.size() ) { neo.push_back(nums2[c]); current++; c++; } else if (c == nums2.size()) { neo.push_back(nums1[b]); current++; b++; } else { if (nums1[b] <= nums2[c]){ neo.push_back(nums1[b]); b++; current++; } else { neo.push_back(nums2[c]); c++; current++; } } if (current == (a + 1) / 2) { outcome = neo[current - 1]; break; } } } else { int current = 0; int b = 0; int c = 0; while (b != nums1.size() || c != nums2.size()) { if (b == nums1.size() ) { neo.push_back(nums2[c]); current++; c++; } else if (c == nums2.size()) { neo.push_back(nums1[b]); current++; b++; } else { if (nums1[b] <= nums2[c]) { neo.push_back(nums1[b]); b++; current++; } else { neo.push_back(nums2[c]); c++; current++; } } if (current == (a + 2) / 2) { double x = neo[current - 1]; double y = neo[current - 2]; outcome = (x + y) / 2; break; } } } return outcome; }};
这里面主要是用到上学期数据结构学到的方法,就是用两个int变量分别标记两个向量的当前位置,判断哪个比较小,小的插入到新的向量中,同时所在的向量的位置标记加1,若一个向量已经插入完毕,那么重复插入剩下的那个向量的所有元素,这样能将两个排列好的向量合并成一个排列好的向量,由于题目只要求中位数,因此只需要插入的个数达到总元素数的一半即可得到所求(此处需要分开总数为奇数和偶数两种情况考虑),这也是循环终止的条件。
0 0
- Median of Two Sorted Arrays(hard)
- [Hard]Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays Hard
- 4. Median of Two Sorted Arrays Hard
- No4(Hard) Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays (Hard)
- LeetCode 4. Median of Two Sorted Arrays(Hard)
- <LeetCode><Hard> 4 Median of Two Sorted Arrays
- [4, Hard, C++] Median of Two Sorted Arrays
- Hard-题目50:4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays(Hard)
- Leetcode 4. Median of Two Sorted Arrays (Hard) (cpp)
- LeetCode第四关:Median of Two Sorted Arrays --> Difficulty: Hard
- LeetCode hard 4. Median of Two Sorted Arrays
- Leetcode解题笔记 4.Median of Two Sorted Arrays [Hard]
- Leetcode 4. Median of Two Sorted Arrays[Hard]
- 4. Median of Two Sorted Arrays 【Hard】 分治法
- 算法第三周Median of Two Sorted Arrays[hard]
- C++ Socket 学习笔记
- java--javaWeb--终极版JDBCUtils,使用事务、commons-dbutils、c3p0
- android.widget.FrameLayout cannot be cast to android.widget.Button 问题
- Mac下Apktool的配置与应用
- 虚函数与多态
- Median of Two Sorted Arrays(hard)
- HTML5中input背景提示文字(placeholder)的CSS美化
- 链表常见面试题
- JAVAweb开发技术-------(三)JSP (封装自己的标签库)
- SharedPreferences存储图片对象与获取
- 从git仓库中下载项目到Studio中
- 求连续子数组的最大和---2017滴滴笔试编程1
- 转:npm 模块安装机制简介
- runtime从入门到精通(五)—— 消息发送和消息转发