lintcode 简单查找

描述

对于两个数组,第一个数组可能包含可重复的整数,第二个数组是第一个数组的子集。返回的数组的长度与第二个数组相同。对于第二个数组中的每个元素a,第一个数组中有多少个数字<=a。

样例

1

输入:nums = [3, 2, 4, 3, 5, 1],sub = [2, 4]
输出:[2, 5]
解释:<=2的数字[1,2],<=4的数字[1,2,3,3,4]

2

输入:nums = [3, 1, 2, 3, 3, 1],sub = [1,3]
输出:[2,6]
解释:<=1的数字[1,1],<=3的数字[1,1,2,3,3,3]

思路

两种方法

1

暴力的遍历两个数组

2

将第一个数组排序,然后使用upper_bound函数计算小于等于sub数组中的数

代码

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
/**
* @param nums:
* @param sub:
* @return: return a Integer array
*/
vector<int> SimpleQueries (vector<int> &nums, vector<int> &sub) {
// write your code here


vector<int> res;
for (int i = 0; i < sub.size(); i++){
int temp = sub[i];
int n = 0;
for (int j = 0; j < nums.size(); j++) {
if (temp >= nums[j])
n++;
}
res.push_back(n);
}
return res;
}
};

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution
{
public:
/**
* @param nums:
* @param sub:
* @return: return a Integer array
*/
vector<int> SimpleQueries (vector<int> &nums, vector<int> &sub)
{
sort(nums.begin(), nums.end());
vector<int> res;
for(int i; i < sub.size(); i++) {
int s = sub[i];
res.push_back(upper_bound(nums.begin(), nums.end(), s) - nums.begin());
}
return res;
}
};
-------------end of file thanks for reading-------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值