Leetcode平台上的Median of Two Sorted Arrays题目用Java快排实现
来源:互联网 发布:自动弹钢琴的软件 编辑:程序博客网 时间:2024/06/05 13:31
Leetcode平台上的Median of Two Sorted Arrays题目,大意就是找两个已排序数组的中位数。今天先用快排的方式实现一下,代码如下:
快排递归深度logn,每一层的操作复杂度是O(n)所以复杂度应该是O(nlogn)。
There are two sorted arrays A and B 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)).
public class Solution { public static int[] C; public static void quickSort(int a[],int low, int high){ if(low < high){ int i = low; int tmp; for(int j = low; j< high; j++){ if(a[j]<=a[high]){ tmp = a[i]; a[i] = a[j]; a[j] = tmp; ++ i; } } tmp = a[i]; a[i] = a[high]; a[high] = tmp; quickSort(a,low,i-1); quickSort(a,i+1,high); } } public static double findMedianSortedArrays(int A[], int B[]) { double i ; //combine these two arrays into a new array C int l = A.length+B.length; C = new int[l]; System.arraycopy(A, 0, C, 0, A.length); System.arraycopy(B, 0, C, A.length, B.length); quickSort(C,0,l-1); //for(int ii = 0; ii < l; ii ++) //System.out.println(C[ii]); if(l%2 == 0) i = (double) ((C[l/2]+C[l/2-1])/2.0); else i = (double) C[(l-1)/2]; return i; } public static void main(String args[]){ int[] A = {1}; int[] B = {}; double median = findMedianSortedArrays(A,B); System.out.println(median); }}
快排递归深度logn,每一层的操作复杂度是O(n)所以复杂度应该是O(nlogn)。
对于快排能AC我表示相当意外,只能说leetcode平台给的测试用例不够强壮。如果给一个倒序排好序的数组,我这个快排就死掉了,相当于冒泡阿。
今天再用堆的思想实现一下,复杂度应该比这个快排低一些。
谢谢木易先森的指导!
0 0
- Leetcode平台上的Median of Two Sorted Arrays题目用Java快排实现
- Leetcode平台上的Median of Two Sorted Arrays题目用Java堆算法实现
- [Leetcode] Median of Two Sorted Arrays (Java)
- [LeetCode][Java] Median of Two Sorted Arrays
- Median of Two Sorted Arrays --leetcode java
- LeetCode : Median of Two Sorted Arrays [java]
- leetcode:Median of Two Sorted Arrays 【Java】
- [LeetCode]Median of Two Sorted Arrays(Java)
- leetcode Median of Two Sorted Arrays(Java)
- Leetcode-Median of Two Sorted Arrays (java)
- [LeetCode][4]Median of Two Sorted Arrays解析 -Java实现
- leetcode:4. Median of Two Sorted Arrays(Java实现)
- Java实现Median of Two Sorted Arrays
- LeetCode【4】. Median of Two Sorted Arrays --思路图解与java的不同方法实现
- LeetCode题目笔记(三) -- Median of Two Sorted Arrays
- LeetCode算法题目:Median of Two Sorted Arrays
- LeetCode 题目 4. Median of Two Sorted Arrays
- LeetCode题目:4.Median of Two Sorted Arrays
- 重装系统那些事儿
- JAVA中堆和栈的区别
- 写一个进度条~~
- JDK配置
- 产品管理体系结构
- Leetcode平台上的Median of Two Sorted Arrays题目用Java快排实现
- JDBC中文查询问题
- Object-c基础知识之内存管理(二)
- 10.3OJ
- socket.io系列二 聊天应用
- 10.4抽象类
- Java常见面试题笔试题
- 代做毕业设计杂感……
- ProcessExplorer查看windows进程的利器