LeetCode hard 4. Median of Two Sorted Arrays
来源:互联网 发布:大话数据结构知乎 编辑:程序博客网 时间:2024/06/07 15:55
这道题的难度也是hard,通过率21%,但事实上这道题目并不难,估计也就中等难度吧,然而看到标签的我是崩溃的,标签是二分搜索,分治,数组。然而我就用了一个类似归并的东西,或者说就是暴力解出来的,但是我过了啊,气不气?我们只关心结果,不要在乎过程。
--------------------题目-----------------------
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)).
Example 1:
nums1 = [1, 3]nums2 = [2]The median is 2.0
Example 2:
nums1 = [1, 2]nums2 = [3, 4]The median is (2 + 3)/2 = 2.5------------------题解-------------------------
题目是不是很熟悉,两个已经排好序的数组,简直就是归并排序一模一样啊,所以我选择归并,不知道分治二分要怎么做,建一个向量,然后每次向向量中添加两个数组最小的一个数,然后把这个数删除,直到找到了中位数即可,是不是很简单,时间复杂度是O(n+m),其实最后提交后我这也不是最慢的,甚至还超过了27%的人。
#include<vector>class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int n=nums1.size();int m=nums2.size();int t=(m+n)/2;//计算中位数的位置int k=1;int index1=0;//int index2=0;//相当于一个指针记录数组的首位vector<int> sorted;for(k=0;k<=t+1;k++){if(index1==n)//给出的数组到了最后,下面一样{int temp=t+1-k;while(temp--){sorted.push_back(nums2[index2]);index2++;}break;}else if(index2==m){int temp=t+1-k;while(temp--){sorted.push_back(nums1[index1]);index1++; }break;}else if(nums1[index1]<nums2[index2])//添加一个最小的数到向量中{sorted.push_back(nums1[index1]);index1++; }else{sorted.push_back(nums2[index2]);index2++; }}if((m+n)%2==0)return (double)(sorted[t]+sorted[t-1])/2;elsereturn (double)sorted[t]; }};代码很简单,可能我并没有按照出题人的思路来,走了捷径,但我们老师说过,一切以程序员的效率为主,所以以最快的思路想出来就好啦,规则就是用来打破的嘛,毕竟他时间复杂度没有限制那么死就说明这种方法是可行的。大家可以研究一下出题人的思路,最近准备考试就没时间想那么多了,good luck。顺便分享一句今天看到的一句话吧:有一种人生是可以成功到让金钱跪下来。讲的是中国工程院首批院士刘先林院士为了做好一场报告,七十八岁高龄在高铁二等座上伏案专注画图纸。有图有真相,大家一起共勉吧。
------------------------------手动分割线-----------------------------
see you next illusion
阅读全文
0 0
- leetcode 4. Median of Two Sorted Arrays(Hard)
- Leetcode 4. Median of Two Sorted Arrays (Hard) (cpp)
- LeetCode 4. Median of Two Sorted Arrays(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
- 4. Median of Two Sorted Arrays Hard
- <LeetCode><Hard> 4 Median of Two Sorted Arrays
- LeetCode第四关:Median of Two Sorted Arrays --> Difficulty: Hard
- [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
- 选择排序
- Markdown 学习
- XL3常用MAC使用快捷键及使用技巧
- JAVA设计模式之工厂模式(简单工厂模式+工厂方法模式)
- HDU 2588 数论 欧拉函数
- LeetCode hard 4. Median of Two Sorted Arrays
- jquery对表单元素的取值和赋值
- bzoj 3444: 最后的晚餐
- LeetCode:Path Sum II
- android 鏈接 pc 端本地服務器 Connection to http://10.0.2.2:8080 refused
- 一些细小的知识
- POJ3259---Wormholes(最短路:验证存在负环)
- C++中四种强制转换符
- 今天发现了WinHex的一个有趣汉化方法