标签:dia 循环 解法 ble EDA array arrays solution style
这里我有两种解法,第一种执行时间是157ms,通过两个for循环排序(有点多余)效率比较慢:
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; int i = 0; int j = 0; double res = 0; int[] nums3 = new int[len1 + len2]; while (i < len1) { nums3[i] = nums1[i]; i++; } while (j < len2) { nums3[len1] = nums2[j]; len1++; j++; } int len3 = nums3.length; int temp = 0; for (int h = 0; h < len3; h++) { for (int k = 1; k < len3; k++) { if (nums3[k - 1] > nums3[k]) { temp = nums3[k - 1]; nums3[k - 1] = nums3[k]; nums3[k] = temp; } } } if (len3 % 2 == 0) { int m = len3 / 2; res = (float)(nums3[m] + nums3[m - 1]) / 2; } if (len3 % 2 == 1) { int n = (len3 - 1) / 2; res = nums3[n]; } return res; } }
通过优化后的代码,执行时间是3ms,明显效率快很多:
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; int i = 0; int j = 0; double res = 0; int[] nums3 = new int[len1 + len2]; int len3 = nums3.length; int temp = 0; while(i < len1 && j < len2) { if (nums1[i] < nums2[j]) { nums3[temp] = nums1[i]; temp++; i++; } else { nums3[temp] = nums2[j]; temp++; j++; } } while (i < len1) { nums3[temp] = nums1[i]; temp++; i++; } while (j < len2) { nums3[temp] = nums2[j]; temp++; j++; } if (len3 % 2 == 0) { int m = len3 / 2; res = (float)(nums3[m] + nums3[m - 1]) / 2; } if (len3 % 2 == 1) { int n = (len3 - 1) / 2; res = nums3[n]; } return res; } }
标签:dia 循环 解法 ble EDA array arrays solution style
原文地址:https://www.cnblogs.com/pusan/p/12228644.html