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;
    }
    

  • 相关阅读:
    jQuery的核心对象、原型对象、静态方法、动态方法
    请写出css中选择器(元素选择器、类选择器、id选择器)的优先级顺序,和当各种选择器组合时,优先级的计算规则是什么?
    css3中的box-sizing常用的属性有哪些?分别有什么作用?
    不同域的页面如何通信(跨域)
    浮动与定位
    获取DOM元素的方式有哪些
    简要说明盒子模型和flex布局
    牛逼哄哄的对象深复制
    欧拉函数
    P2659 美丽的序列
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787063.html
Copyright © 2011-2022 走看看