jiler的LeetCode学习笔记 java版本Median of Two Sorted Arra
2015-03-15 22:48
323 查看
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)).
问题不难理解,做完之后,看了提示,因为今天的代码运行时500ms,有点难以忍受。提示信息是Divide and Conquer,Array,Binary Search。这个我都没用过。数据结构学习真的忘了很多,因此打算,明天可能不更新这类题目了,仅限于用自己记得住的可怜的那点知识,这样刷题,没用。因此,明天学习数据结构。
解题思想不难:合并两个数组是主要部分,完事看奇偶。代码如下:
问题不难理解,做完之后,看了提示,因为今天的代码运行时500ms,有点难以忍受。提示信息是Divide and Conquer,Array,Binary Search。这个我都没用过。数据结构学习真的忘了很多,因此打算,明天可能不更新这类题目了,仅限于用自己记得住的可怜的那点知识,这样刷题,没用。因此,明天学习数据结构。
解题思想不难:合并两个数组是主要部分,完事看奇偶。代码如下:
public double findMedianSortedArrays(int A[], int B[]) { //新建arraylist 存储两个数组的合并元素,因为未知长度,所以不用新的数组。 ArrayList<Integer> al = new ArrayList<Integer>(); //两个指针,指向两个数组,使其合并 int i=0; int j=0; while (i<A.length && j<B.length) { if (A[i]<B[j]) { al.add(A[i]); i++; continue; }else if (A[i]==B[j]) { al.add(A[i]); al.add(B[j]); i++; j++; continue; } else{ al.add(B[j]); j++; continue; } } //处理未合并完的另一个数组,A或者B while (i<A.length ){ al.add(A[i]); i++; } while (j<B.length ){ al.add(B[j]); j++; } //因为之前是有序的,因此不用排序,找到中位数即可。 double s = 0; double b = 0; double a = 0; if (al.size()%2==0) { a = (Integer)(al.get(al.size()/2-1)); b = (Integer)(al.get(al.size()/2)); s = (a+b)/2; } if (al.size()%2==1) { b = (Integer)(al.get(al.size()/2)); s=b; } return s; }
相关文章推荐
- LeetCode, Median of Two Sorted Arrays, Java Solution, O(m+n), O(log(m+n))
- [LeetCode][Java] Median of Two Sorted Arrays
- leetcode:Median of Two Sorted Arrays 【Java】
- LeetCode : Median of Two Sorted Arrays [java]
- Leetcode 4 Median of Two Sorted Arrays Java
- jiler的LeetCode学习笔记 java版本Two Sum
- LeetCode Median of Two Sorted Arrays(JAVA)
- [LeetCode]Median of Two Sorted Arrays(Java)
- Median of Two Sorted Array leetcode java
- LeetCode题目笔记(三) -- Median of Two Sorted Arrays
- Leetcode平台上的Median of Two Sorted Arrays题目用Java快排实现
- LeetCode – Median of Two Sorted Arrays Java
- 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays
- (leetcode)4.两个有序数列中间的第n个数 Median of Two Sorted Arrays--Java
- LeetCode 笔记系列一 Median of Two Sorted Arrays
- jiler的LeetCode学习笔记 java版本Longest Substring Without
- 【leetcode with java】4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays (Java)
- Leetcode: Median of Two Sorted Arrays. java.