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

题目要求如下:

在长度为n的一维数组A中,数组元素为互不相同的
整型数。若存在这样的数x,它大于它左侧所有数,
小于右侧所有数,则称x为A中的一个中间数。例如:
若数组A={3, 1, 6, 4, 5, 7, 9, 8, 10, 14, 12},则A中有
中间数7和10。试设计一个线性时间复杂度的算法,
找出给定数组A中的所有中间数。

实现思路:

先倒序遍历数组, 获得每一个元素右边的最小值。然后正序遍历数组,获取每个元素左边的最大值,判定左边的最大值是否与右边的最小值相等,相等的话则输出该元素。

代码实现:

#include "pch.h"
#include <iostream>
#include<algorithm>
using namespace std;

void findMedium(int arr[], int len)
{
	//先输出原数组
	for (int i = 0; i < len; i++)
	{
		cout << arr[i];
		if (i != len - 1)
			cout << " ";
		else
			cout << endl;
	}
	int* rightMin = new int[len];
	rightMin[len - 1] = arr[len - 1];
	for (int i = len-2; i >=0; i--)
	{
		rightMin[i] = min(rightMin[i + 1], arr[i]);
	}
	int left_max = 0;
	for (int i = 0; i < len; i++)
	{
		left_max = max(left_max, arr[i]);
		if (left_max == rightMin[i])
		{
			cout << arr[i] << ":大于数组左边数,小于数组右边数" << endl;
		}
	}
}
int main()
{
	int data[7] = { 7,10,2,6,19,22,32 };
	findMedium(data, 7);
}

实现效果:

猜你喜欢

转载自blog.csdn.net/weixin_41106545/article/details/83213948
今日推荐