leetcode 4. Median of Two Sorted Arrays
来源:互联网 发布:淘宝介入卖家退货拒收 编辑:程序博客网 时间:2024/05/29 06:26
//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 Solution {public static void main(String[] args) {int[] a = {2,3};int[] b = {};double result = findMedianSortedArrays(a, b);System.out.println(result);}public static double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int res[] = new int[m+n]; int i = 0; int a = 0;//数组1的index int b = 0;//数组2的index while(i<m+n&&a<nums1.length&&b<nums2.length){//依次比较两数组中的元素,将较小的加入res[]数组中 if(nums1[a]<nums2[b]){ res[i] = nums1[a]; a++; i++; }else{ res[i] = nums2[b]; b++; i++; } } while(a<nums1.length){//将数组1多余出来的数据加到res尾部 res[i] = nums1[a]; a++; i++; } while(b<nums2.length){//将数组2多余出来的数据加到res尾部 res[i] = nums2[b]; b++; i++; } if(i%2 == 1){//根据res中元素个数的不同返回相应的中间值,偶数个元素要求出中间值,如input:{2,3},output:2.5 return res[(i-1)/2]; }else{ return (res[i/2]+res[i/2-1])/2.0; } } }
0 0
- [LeetCode]4.Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- LeetCode --- 4. Median of Two Sorted Arrays
- [Leetcode] 4. Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 【leetcode】4. Median of Two Sorted Arrays
- Leetcode-4.Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- [leetcode]4. Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- [LeetCode]4. Median of Two Sorted Arrays
- leetCode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- 对任意十个数求和(5)
- Spring容器启动后注入service到Servlet并自动执行
- 阶乘
- iOS原生键盘类型
- vb
- leetcode 4. Median of Two Sorted Arrays
- C语言基础函数 已知摄氏度求华氏度
- 一点点
- jQuery EasyUI 表单
- don't run elasticsearch as root.
- React-native第一课,Button的添加
- HTML + CSS 之替换元素与非替换元素
- 《编写高质量代码 : 改善C#程序的157个建议》读书笔记 1-10
- HDU 1565 1569 方格取数 (最小割)