有两个大小分别为m和n的有序数组A和B。请找出这两个数组的中位数。你需要给出时间复杂度在O(log (m+n))以内的算法。
import java.util.*; public class Solution { public double findMedianSortedArrays (int[] A, int[] B) { double result = 0.0; int[] c = new int[A.length + B.length]; System.arraycopy(A, 0, c, 0, A.length); System.arraycopy(B, 0, c, A.length, B.length); Arrays.sort(c); if(c.length%2==0) { result = (c[c.length/2-1]+c[c.length/2])*1.0/2; } else { result = c[c.length/2]; } return result; } }
public class Solution { public double findMedianSortedArrays(int A[], int B[]) { int na = A.length-1, nb = B.length-1, i = 0; int n = A.length + B.length; int[] total = new int[n]; //归并排序 while(na>=0 && nb>=0){ if(A[na]>B[nb]){ total[i] = A[na]; na--; }else{ total[i] = B[nb]; nb--; } i++; } //合并剩余数组 if(na<0){ for(;nb>=0;nb--){ total[i++] = B[nb]; } }else{ for(;na>=0;na--){ total[i++] = A[na]; } } //获取中位数 int mid = (int)Math.floor(n/2); if(n%2 == 0){ return (float)(total[mid-1]+total[mid])/2; }else{ return (float)total[mid]; } } }
//本题最简单解法 1.链表分两半 2.逆置后一半 3.依次链接两个链表 public ListNode reverse(ListNode head){ if(head==null){ return null; } if(head.next==null){ return head; } ListNode pre= null; ListNode next = null; while (head!=null){ next = head.next; head.next = pre; pre = head; head = next; } return pre; } //将链表分成两半 public ListNode half(ListNode head){ ListNode fast = head; ListNode slow = head; while (fast.next!=null&&fast.next.next!=null){ slow = slow.next; fast = fast.next.next; } ListNode p =slow.next; slow.next = null; return p; } public void reorderList(ListNode head) { if(head==null){ return ; } //两个指针 快慢指针 走到头断开两个链表 ListNode half = this.half(head); //第二个链表逆置 ListNode reverse = reverse(half); //链接这两个链表 head reverse ListNode p = head; ListNode q = reverse; while (p!=null&&q!=null){ ListNode a = p.next; ListNode b = q.next; p.next = q; q.next=a; p =a; q=b; } }
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int[] nums = new int[nums1.length+nums2.length]; int i1=0,i2=0,i=0; while(i<nums.length){ if(i1>=nums1.length) nums[i++] = nums2[i2++]; else if(i2>=nums2.length) nums[i++] = nums1[i1++]; else{ if(nums1[i1]>nums2[i2]) nums[i++] = nums2[i2++]; else nums[i++] = nums1[i1++]; } } if(nums.length%2==1) return nums[(nums.length-1)/2]; else return (nums[nums.length/2]+nums[nums.length/2-1])/2.0; } }
import java.util.*; public class Solution { public double findMedianSortedArrays(int A[], int B[]) { ArrayList<Integer> db = new ArrayList<Integer>(); if(A==null || B == null || A.length+B.length==0)return 0; for(int i = 0; i < A.length; i++)db.add(A[i]); for(int i = 0; i < B.length; i++)db.add(B[i]); Collections.sort(db); return db.size()%2==0 ? (db.get(db.size()/2)+db.get(db.size()/2-1))/2.0 : db.get(db.size()/2); } }