题目:在一个int数组里查找这样的数,它大于等于左侧所有数,小于等于右侧所有数。
答:
#include "stdafx.h" #include <iostream> using namespace std; //数组中大于等于左侧所有数,小于等于右侧所有数的数 void FindSpecialNumber(int *arr, int length) { if (NULL == arr || length <= 0) { return; } int *rightMin = new int[length]; rightMin[length - 1] = arr[length - 1]; for (int i = length - 2; i >= 0; i--) { if (arr[i] > rightMin[i + 1]) { rightMin[i] = rightMin[i + 1]; } else { rightMin[i] = arr[i]; } } int leftMax = arr[0]; for (int i = 0; i < length; i++) { if (leftMax < arr[i]) { leftMax = arr[i]; } if (leftMax == rightMin[i]) { cout<<leftMax<<" "; } }
delete [] rightMin;
rightMin = NULL; } int _tmain(int argc, _TCHAR* argv[]) { int arr[] = {6, 4, 7, 20, 13, 28, 39}; cout<<"数组本身: "; for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { cout<<arr[i]<<" "; } cout<<endl<<"符合的数: "; FindSpecialNumber(arr, sizeof(arr)/sizeof(arr[0])); cout<<endl; return 0; }
运行界面如下: