915. 分割数组

915. 分割数组

按照题目要求,希望left数组越小越好

根据样例可以知道,左右数组的分割点在整个数组最小值的附近

  1. 先找到数组最小值的的位置,以此分割出左右初数组;
  2. 求出左数组中的最大值max_left,右数组中的最小值min_right;
  3. 比较max_left和min_right的大小,找到比max_left大的min_right;
  4. 在找到距离整个数组最小值最近的min_right的位置;
  5. 得到最终的答案
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <set>
#include <numeric>
using namespace std;





class Solution {
public:
	int partitionDisjoint(vector<int>& A) 
	{
		vector<int>num = A;
		sort(num.begin(), num.end());
		if (num == A)
			return 1;
		num = A;
		int _min = *min_element(num.begin(), num.end());
		auto pos_min = find(num.rbegin(), num.rend(), _min);
		int max_left = *max_element(pos_min, num.rend());
		if (max_left == *pos_min)
			return 1;
		while (1)
		{
			auto temp = min_element(num.rbegin(), pos_min);
			if (*temp < max_left)
			{
				pos_min = temp;
				max_left = *max_element(pos_min, num.rend());
			}
			else
			{
				pos_min = temp;
				while (*pos_min<=*temp)
				{
					temp++;
				}
				return distance(temp, num.rend());
			}
		}
		return A.size() - 1;
	}

};

int main()
{
	
	/*int N = 100;
	vector<vector<int>>edges = { {{74, 34},{67, 44},{81, 40},{1, 97},{44, 88},{95, 23},{77, 78},{67, 29},{98, 1},{89, 3},{60, 91},{30, 28},{64, 85},{47, 72},{64, 9},{26, 35},{24, 1},{43, 35},{62, 86},{92, 86},{59, 89},{31, 3},{31, 92},{1, 33},{54, 68},{57, 63},{2, 3},{36, 64},{6, 9},{3, 67},{99, 70},{9, 47},{45, 16},{94, 92},{22, 9},{56, 31},{89, 84},{40, 31},{37, 38},{57, 52},{75, 76},{1, 26},{65, 79},{5, 39},{96, 47},{55, 14},{83, 54},{6, 32},{11, 26},{8, 40},{32, 69},{32, 14},{78, 79},{34, 92},{31, 75},{39, 45},{3, 79},{71, 31},{82, 74},{51, 58},{27, 35},{60, 70},{31, 51},{53, 74},{64, 60},{84, 90},{39, 40},{28, 80},{0, 47},{31, 41},{1, 25},{56, 48},{93, 10},{1, 17},{37, 7},{47, 15},{49, 41},{5, 18},{4, 92},{25, 64},{84, 95},{10, 95},{63, 66},{46, 87},{92, 50},{66, 3},{64, 75},{61, 98},{78, 12},{54, 71},{7, 65},{87, 39},{73, 96},{61, 20},{64, 19},{21, 69},{30, 6},{42, 72},{13, 67}} };
*/

	vector<int> num = { 5,0,3,4,5,4,5,5,8,6,10,7,6,10,6,7};
	string S = "Test1ng-Leet=code-Q!";
	Solution s;
	s.partitionDisjoint(num);
	//s.sumOfDistancesInTree(S);
	return 0;
}

附上刚开始做的时候使用的暴力解法

class Solution {
public:
	int partitionDisjoint(vector<int>& A) 
	{
		vector<int>num = A;
		auto i = num.begin() + 1;
		//sort(num.begin(), num.end());
		vector<int>temp1(num.begin(), i);
		vector<int>temp2(i, num.end());
		for (; i !=num.end(); i++)
		{

			int max1 = *max_element(temp1.begin(), temp1.end());
			int min2 = *min_element(temp2.begin(), temp2.end());
			if (max1<=min2)
			{
				return temp1.size();
			}
		}
	}
};

猜你喜欢

转载自blog.csdn.net/kongqingxin12/article/details/83187296
今日推荐