zoukankan      html  css  js  c++  java
  • [面试] 在数组查找这样的数,它大于等于左侧所有数,小于等于右侧所有数

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

    分析:

    最原始的方法是检查每一个数 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;
    }
    

  • 相关阅读:
    最基础的账户余额要怎么在 mysql 实现?
    跳跃表时间复杂度分析推导
    Redis:RDB 中 fork 的使用
    字段、约束和索引在存储过程中的判断
    高效沟通的基本流程
    人月神话--画蛇添足
    课程评价及加分项
    人月神话--提纲挈领
    热词搜索七
    《大道至简:软件工程实践者的思想》
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787063.html
Copyright © 2011-2022 走看看