首页 > 学院 > 开发设计 > 正文

LeetCode 4. Median of Two Sorted Arrays(二叉搜索树的使用)

2019-11-08 03:04:34
字体:
来源:转载
供稿:网友

题意: 给出2个有序的数组,找出2个数组合并后的中位数,直接合并没尝试, 写了个二叉搜索树,直接遍历一遍,找到数就好了, 恩 代码写的像屎一样。

struct node{ int data; node *l,*r; node(){l=r=NULL;} node(int t):data(t){l=r=NULL;}};void insert(node* &root, int val){ if(!root){ root = new node(val); return ; } if(val < root->data){ insert(root->l, val); } else { insert(root->r, val); }}int cnt=0,p1,p2,x,y;double ans;void show(const node* root){ if(!root){ return ; } if(root->l){ show(root->l); } if(cnt==p1)x=root->data; if(cnt==p2)y=root->data;cnt++; if(root->r){ show(root->r); }}class Solution {public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { node *root=NULL; for(int i=0;i<nums1.size();i++){ insert(root, nums1[i]); } for(int i=0;i<nums2.size();i++){ insert(root, nums2[i]); } cnt=0;int sum = nums1.size()+nums2.size(); p1 = sum/2-1; p2=sum/2; show(root); if(sum&1){ ans = y; } else { ans = (x+y)/2.0; } return ans; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表