915. Partition Array into Disjoint Intervals

2018/10/06 leetcode 共 879 字,约 3 分钟

title

problem link

Given an array A, partition it into two (contiguous) subarrays left and right so that:

Every element in left is less than or equal to every element in right.

left and right are non-empty.

left has the smallest possible size.

Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.

Example 1:

Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:

Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]

solution

数组从中分离,要求左边都<=右边 可以记录每个index, 从左到右的max(i), 从右到左的min(i), min(i)>=max(i)的位置就是想要的

class Solution {
public:
	int partitionDisjoint(vector<int>& A) {
		vector<int> left, right;
		int maxx = INT_MIN;
		for (int i = 0; i < A.size(); i++) {
			left.push_back(maxx);
			maxx = max(A[i], maxx);
		}
		left[0] = INT_MAX;
		int res;
		int minx = INT_MAX;
		for (int i = A.size() - 1; i >= 0; i--) {
			minx = min(minx, A[i]);
			if (minx >= left[i]) {
				res = i;
			}
		}
		return res;
	}
};

Search

    Table of Contents