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
原创粉丝点击