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
思路很简单,把两个数组的数字全部放到List里面,排序,偶数个就输出中间两个和的一半,奇数就输出中间一个。
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<Integer>();
for(int i = 0;i<nums1.length;i++){
list.add(nums1[i]);
}
for(int i = 0;i<nums2.length;i++){
list.add(nums2[i]);
}
Collections.sort(list, new Comparator<Integer>() {
public int compare(Integer arg0, Integer arg1) {
return arg0.compareTo(arg1);
}
});
int length = nums1.length + nums2.length;
if(length%2==0){
return (list.get(length/2-1) + list.get(length/2))/2.0;
}else {
return list.get((length+1)/2-1);
}
}
这段时间在做前台,真是做的心累,不过有一点收获,即使没有一点前台基础,这两个星期天天啃js代码,还是能做出一个看的过去的页面,重要的还是静下来啃代码,大家智商都差不多,没有谁更聪明一些,别人能做的好看,你为什么就不行?昨天的取最长子串的题目还欠着,得抽空把它解决了,拖着拖着就忘了。