Median of Two Sorted Arrays

225 篇文章 0 订阅
50 篇文章 0 订阅
这是一篇关于LeetCode上两排序数组中位数问题的解析。通过合并两个已排序数组并利用排序性质找到中位数。文章提到在处理边界条件如[] [1], [1][1]时遇到挑战,强调了细节和严谨思考的重要性。" 109480760,8548657,细粒度行为识别:深度学习挑战与策略,"['深度学习', '行为识别', '数据集构建', '模型优化', 'LSTM模型']
摘要由CSDN通过智能技术生成

leetecode 上的一道题: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)).


实现代码:

package leetcode;

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    	
    int total = nums1.length+nums2.length;
    int median;
    int p=0,p1=0,p2=0;
    int temp[]=new int[total];
    boolean isOdd = false;
    if(total%2 != 0){
    	isOdd = true;
    }
   
    while(true){
    	//grow
    	//System.out.println("xx");
    	if( p1<nums1.length && p2<nums2.length && nums1[p1] < nums2[p2] ){
    		temp[p]=nums1[p1];
    		p1++;
    		p++;
    		
    		
    	}
    	 
    	if( p1<nums1.length && p2<nums2.length && nums1[p1] >= nums2[p2]) {
    		temp[p]=nums2[p2];
    		p2++;
    		p++;
    		
    	}
    	
    	
    	//rest
    	if(p1 == nums1.length && p2 < nums2.length ||nums1.length==0 && p2 < nums2.length){
    		//go p2
    		temp[p]=nums2[p2];
    		p2++;
    		p++;
    		//System.out.println(temp[p-1]);
    		
    		
    	}
    	if(p2 == nums2.length && p1 < nums1.length ||nums2.length==0 && p1 < nums1.length){
    		//go p2
    		temp[p]=nums1[p1];
    		p1++;
    		p++;
    		
    		
    	}
    	
    	if(p > total/2){
    		break;
    	}
    	
    	
    	
    }
    
    
  
   
    if(isOdd){
    	
    	  return temp[total/2];
    }
  
    else{
    	
    	return
        		(temp[total/2-1]+temp[total/2])/2.0;
    	
    }
    	
    }
    
    public static void main(String args[]){
    	
    	Solution s = new Solution();
    	int nums1 []={3,4,7};
    	int nums2 []= {2};
    	System.out.println(s.findMedianSortedArrays(nums1, nums2));
    	
    	
    }
    
}

基本思路是:因为是两个已经排好序的数组,那么可以将两个数组合并成一个数组,再去计算中位数。实现的话用到的应该是数据结构里面的基础知识。

提交的时候对于特殊值 [] [1], [1][1] 的情况报错,花了一些时间修改边界条件。往往细节的地方很重要,觉得思考需要更严谨一些。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值