找出两个含有相同元素个数的递增数列中第n小的数
来源:互联网 发布:免费身份证读取软件 编辑:程序博客网 时间:2024/05/21 20:52
1.Description
You are given two arrays
- (a) Describe an
O(logn) time algorithm to find thenth smallest of the2n keys. - (b) Describe an
O(logn) time algorithm to find then2 th smallest (i.e., the median) of the2n keys assuming thatn is even.
public class BinarySearch{public static int Find(int seq1[],int seq2[],int left1,int right1,int left2,int right2,int key){int mid1=(left1+right1)/2;int mid2=(left2+right2)/2;if(left1>right1){int index=left2+key-1;return seq2[index];}if(left2>right2){int index=left1+key-1;return seq1[index];}if(key<=(mid1-left1+mid2-left2+1)){if(seq1[mid1]<=seq2[mid2]){right2=mid2-1;return Find(seq1,seq2,left1,right1,left2,right2,key);}else{right1=mid1-1;return Find(seq1,seq2,left1,right1,left2,right2,key);}}else {//remove the elements which is smaller than the median valueif(seq1[mid1]<=seq2[mid2]){int keyChange=mid1+1-left1;left1=mid1+1;key=key-keyChange;return Find(seq1,seq2,left1,right1,left2,right2,key);}else{int keyChange=mid2+1-left2;left2=mid2+1;key=key-keyChange;return Find(seq1,seq2,left1,right1,left2,right2,key);}}}public static void main(String[] args){int seq1[]={2,3,5,8,10};int seq2[]={4,6,7,9,12};int left1=0,left2=0,right1=seq1.length-1,right2=seq2.length-1;int x1=seq1.length;int x2=seq1.length/2;int x1Result=Find(seq1,seq2,left1,right1,left2,right2,x1);System.out.println("the "+x1+"th smallest number is "+x1Result);int x2Result=Find(seq1,seq2,left1,right1,left2,right2,x2);System.out.println("the "+x2+"th smallest number is "+x2Result);}}Screenshot of the result:
- 找出两个含有相同元素个数的递增数列中第n小的数
- 【一个小实验】找出两个数组中相同的元素
- 两个数组中找出相同的元素
- 找出两个数组中相同的元素
- 一个整数数列,元素取值可能是1~N(N是一个较大的正整数)中的任意一个数,相同数值不会重复出现。设计一个算法,找出数列中符合条件的数对的个数,满足数对中两数的和等于N+1
- 找出二进制表示中1的个数相同,且大小最接近的那两个数
- 从100W个数中最快找出两个相同的数
- 找出1001个数(区间1~1000)中重复出现的数(有两个相同)
- 删除数组中相同的数,统计两个数组中重复数个数并把不同数找出来
- 判断两个数组中是否含有相同的元素
- 从n个元素中找出第K小的数 利用快排的思想来实现
- 找出数列中个数大于总数一半的元素
- Matlab如何找出两个矩阵中相同的元素
- 找出两个有序数组中相同的元素
- R-找出两个数列中的相同元素
- 从n个数中找出每个数的重复数
- C++找出两个数组中不相同的数
- 给定一个正整数,找出一个数:与其二进制表示中1的个数相同,比该数小,而且最接近
- 用 LaTeX 排版编程技术书籍的一些个人经验
- ACM_1240_String和char转换
- OpenCV Mat类矩阵元素访问
- ACM进阶指南
- Tornado - Authentication - tornado.web.authenticated经典写法,带认真
- 找出两个含有相同元素个数的递增数列中第n小的数
- CollectionView导致内存泄露?
- 谈谈如何学习
- 对技术没有激情怎么办?
- Java StringBuffer类常用方法简介
- eclipse 下往项目添加文件或文件夹的方法
- Java:多线程等待所有线程结束(CountDownLatch/CyclicBarrier)
- 384. Strike the iron while it is hot. 趁热打铁
- XP下硬盘安装ubuntu11.10(其实很简单的)