牛客真题(9)-六一儿童节

今天继续刷牛客真题,给两个数组,判断其中一个数组中最多有多少个比另一个数组大的数。

分析:
这是贪心算法问题,首先对输入的数组进行排序,按照从小到大的顺序排序,然后比较其中一个数组中的每一位于另一个数组的每一位,如果存在一对,那么结果加一,直到这个数组遍历完。这个也类似于双指针法,通过同时遍历两个数组的方式,比较大小。

问题:
1、数组的输入,定义容器,然后在循环中输入每一位。
2、C++和Python的双指针法的使用。

附上C++代码:

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    int n;
    cin>>n;
    vector<int>h(n);
    for(int i=0;i<n;i++){
        cin>>h[i];
    }
    int m;
    cin>>m;
    vector<int>w(m);
    for(int j=0;j<m;j++){
        cin>>w[j];
    }
    int res=0;
    sort(h.begin(),h.end());
    sort(w.begin(),w.end());
    for(int i=0,j=0;i<n&&j<m;j++){
        if(w[j]>=h[i]){
            res++;
            i++;
        }
    }
    cout<<res<<endl;
    return 0;
}

附上Python代码:

n=int(input())
h=list(map(int,input().split()))
m=int(input())
w=list(map(int,input().split()))

sorted(h)
sorted(w)
k=0
result=0
for i in range(m):
    for j in range(k,n):
        if w[i]>=h[j]:
            result+=1
            k+=1
            break
print(result)

猜你喜欢

转载自blog.csdn.net/JerryZengZ/article/details/88943722