Median of Two Sorted Arrays --leetcode java
来源:互联网 发布:谷歌for mac官方下载 编辑:程序博客网 时间:2024/05/22 14:13
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)).——————-
public class FindMedianSortedArrays { public double findMedianSortedArrays(int[] nums1, int[] nums2) { double median = -1; int length_sum = nums1.length + nums2.length; int[] nums3 = merge(nums1, nums2, length_sum); if (length_sum % 2 == 1) { median = nums3[(int) Math.floor(length_sum / 2)]; } else { //必须强制类型转换,否则结果转化为整形 median = (double)(nums3[length_sum / 2] + nums3[length_sum / 2 - 1]) /(double) 2; } return median; } public int[] merge(int[] nums1, int[] nums2, int length_sum) { if (nums1.length == 0) return nums2; if (nums2.length == 0) return nums1; int[] nums3 = new int[length_sum]; //new一个新的数组,在原来数组的最后多加一个哨兵,避免越界 int[] a=new int[nums1.length+1]; int[] b=new int[nums2.length+1]; for(int i=0;i<nums1.length;i++){ a[i]=nums1[i]; } for(int j=0;j<nums2.length;j++){ b[j]=nums2[j]; } //设置一个哨兵牌,避免数组越界 a[nums1.length]=Integer.MAX_VALUE; b[nums2.length]=Integer.MAX_VALUE; int i = 0, j = 0; for (int m = 0; m < length_sum; m++) { if (a[i] < b[j]) { nums3[m] = a[i]; i = i + 1; } else { nums3[m] = b[j]; j = j + 1; } } return nums3; }}
0 0
- [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 – Median of Two Sorted Arrays Java
- [leetcode NO.2] Median of Two Sorted Arrays (JAVA)
- leetcode第四题:Median of Two Sorted Arrays (java)
- 【leetcode with java】4 Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays Java
- leetcode 004 Median of Two Sorted Arrays(java)
- LeetCode(java)4. Median of Two Sorted Arrays
- [LeetCode][4]Median of Two Sorted Arrays解析 -Java实现
- leetcode: 4. Median of Two Sorted Arrays (java)
- Leetcode 第四题< Median of Two Sorted Arrays>(Java)
- 解决子窗口(视图)截获父窗口消息的2个办法(MFC)
- Canvas:使用JavaScript进行基本图形操作与处理
- 【ACM】最长公共子序列
- AndroidStudio使用GreenDao实战
- SQL Server类型与C#类型对应关系
- Median of Two Sorted Arrays --leetcode java
- 安卓代码混淆注意事项
- 文件读写操作笔记(2)
- 常见的几种拓扑文件格式:graphml,brite,tcl
- 基本排序算法--选择排序
- LaTeX中多图处理
- Android-画廊实现 (Gallery , ImageSwitch)
- 查找附近的xxx 球面距离以及Geohash方案探讨
- 设计模式笔记(六)--适配器模式、外观模式