[面试] 在数组查找这样的数,它大于等于左侧所有数,小于等于右侧所有数

在数组里查找这样的数,它大于等于左侧所有数,小于等于右侧所有数。

分析:

最原始的方法是检查每一个数 array[i] ,看是否左边的数都小于等于它,右边的数都大于等于它。这样做的话,要找出所有这样的数,时间复杂度为O(N^2)。

其实可以有更简单的方法,我们使用额外数组,比如rightMin[],来帮我们记录原始数组array[i]右边(包括自己)的最小值。假如原始数组为: array[] = {7, 10, 2, 6, 19, 22, 32}, 那么rightMin[] = {2, 2, 2, 6, 19, 22, 32}. 也就是说,7右边的最小值为2, 2右边的最小值也是2。

有了这样一个额外数组,当我们从头开始遍历原始数组时,我们保存一个当前最大值 max, 如果当前最大值刚好等于rightMin[i], 那么这个最大值一定满足条件。还是刚才的例子。

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");
// 查找这样的数,左边所有的数字都小于它,右边所有的数字都大于它。
using namespace std;
const int N = 1005;
int findNum(int *arr, int n) {
	if(arr == NULL) return 0;
	int *rmin = new int[n];
	int cnt = 0, i = n-1;
	rmin[i] = arr[i];
	for(i = n-2; i >= 0; i--) {
		if(arr[i] <= rmin[i+1]) {
			rmin[i] = arr[i];
		}
		else rmin[i] = rmin[i+1];
	}
	int lmax = arr[0];
	for(i = 0; i < n; i++) {
		if(arr[i] > lmax) lmax = arr[i];
		if(rmin[i] == lmax) {
			cnt++;
			cout << arr[i] << ' ';
		}
	}
	cout << endl;
	return cnt;
}
int main() {
	int a[] = {7, 10, 2, 6, 19, 22, 32};
	findNum(a, 7);
	return 0;
}

原文地址:https://www.cnblogs.com/robbychan/p/3787063.html