4. 寻找两个有序数组的中位数

时间:2021-07-13 11:14:23
#include<iostream>
#include<stdio.h>
#include<cstdio>
#include<vector>
#include <algorithm>
#include <functional>
#include<string>
#include<fstream>
#include <sstream>
#include <assert.h>
using namespace std;
class Solution {
public:
	double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 
	{
		if (nums1.size() == NULL && nums2.size() == NULL)//如果为空则返回0
			return 0;
		vector<int> res;//构建一个数组
		for (int i = 0; i<nums1.size(); ++i)
			res.push_back(nums1[i]);
		for (int i = 0; i<nums2.size(); ++i)
			res.push_back(nums2[i]);//将两个数组压入一个数组
		sort(res.begin(), res.end());
		double result;
		if (res.size() % 2)
			result = res[res.size()/2];//如果中间数
		else
			result = (res[res.size()/2] + res[res.size()/2 -1]) / 2.0;//取中间两个数的和的平方
		return result;

			}
};

void trimLeftTrailingSpaces(string &input) {
	input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
		return !isspace(ch);
	}));
}

void trimRightTrailingSpaces(string &input) {
	input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
		return !isspace(ch);
	}).base(), input.end());
}

vector<int> stringToIntegerVector(string input) {
	vector<int> output;
	trimLeftTrailingSpaces(input);
	trimRightTrailingSpaces(input);
	input = input.substr(1, input.length() - 2);
	stringstream ss;
	ss.str(input);
	string item;
	char delim = ',';
	while (getline(ss, item, delim)) {
		output.push_back(stoi(item));
	}
	return output;
}

int main() {
	string line;
	while (getline(cin, line)) {
		vector<int> nums1 = stringToIntegerVector(line);
		getline(cin, line);
		vector<int> nums2 = stringToIntegerVector(line);

		double ret = Solution().findMedianSortedArrays(nums1, nums2);

		string out = to_string(ret);
		cout << out << endl;
	}
	return 0;
} 

4. 寻找两个有序数组的中位数