Leetcode4__findMedianSortedArrays
findMedianSortedArrays
基本思路:通过指针按顺序移动来判断大小顺序,思路和有一道用链表求中间值一样;
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { double mediumNum = 0; //判断奇偶,取中间还是平均 boolean odd = true; mediumNum = (nums1.length+nums2.length)/2 + 1; if((nums1.length+nums2.length)%2==0){ odd = false; } int count = 1; int i = 0; int j = 0; double current = 0; double result = 0; while(count<=mediumNum){ if(i<nums1.length && j<nums2.length ){ if(nums1[i]<nums2[j]){ current = nums1[i]; i++; }else{ current = nums2[j]; j++; } }else if(!(i<nums1.length)){ current = nums2[j]; j++; }else if(!(j<nums2.length)){ current = nums1[i]; i++; } if(odd){ if(count == mediumNum){ result = (double)current; } }else{ if(count == mediumNum -1){ result = current; }else{ result += current; result = (double)result/2 ; } } count++; } return result; } }
运行结果