leetcode 4 Median of Two Sorted Arrays
solution:
1 class Solution { 2 public: 3 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 4 int mid = nums1.size() + nums2.size() ; 5 int is_even = mid % 2; 6 mid = mid / 2 + 1; 7 double tmp = 0; 8 int cur_1 = 0; 9 int cur_2 = 0; 10 for(int i = 0 ;i<mid;i++){ 11 int a = 0; 12 if (cur_1 == nums1.size()){ 13 a = nums2[cur_2]; 14 cur_2 ++; 15 }else if (cur_2 == nums2.size()){ 16 a = nums1[cur_1]; 17 cur_1 ++; 18 }else{ 19 if (nums1[cur_1] < nums2[cur_2]){ 20 a = nums1[cur_1]; 21 cur_1 ++; 22 }else{ 23 a = nums2[cur_2]; 24 cur_2 ++; 25 } 26 } 27 if (is_even == 0 && i == mid - 2){ 28 tmp += a; 29 }else if (i == mid - 1){ 30 tmp += a; 31 } 32 } 33 if (is_even == 0){ 34 tmp = tmp / 2; 35 } 36 return tmp; 37 } 38 };