博客
关于我
【Lintcode】1791. Simple Queries
阅读量:212 次
发布时间:2019-02-28

本文共 1141 字,大约阅读时间需要 3 分钟。

题目地址:

给定一个数组 A A A,再给定一组询问,每次询问 A A A中小于等于 k k k的数有多少个。题目保证 A A A里只含非负整数。

先对 A A A排序,然后开一个数组 c c c c [ i ] c[i] c[i]表示 A A A中等于 i i i的数有多少个,然后再求 c c c的前缀和数组,接着再询问的时候,每次就可以以 O ( 1 ) O(1) O(1)的时间询问出来了。代码如下:

public class Solution {       /**     * @param nums:     * @param sub:     * @return: return a Integer array     */    public int[] SimpleQueries (int[] nums, int[] sub) {           // write your code here        int[] res = new int[sub.length];                int max = 0;        for (int num : nums) {               max = Math.max(max, num);        }                int[] count = new int[max + 1];        for (int num : nums) {               count[num]++;        }                int[] preSum = new int[count.length + 1];        for (int i = 0; i < count.length; i++) {               preSum[i + 1] = preSum[i] + count[i];        }            for (int i = 0; i < sub.length; i++) {           	// 要特判询问的数大于最大值的情况            if (sub[i] > max) {                   res[i] = nums.length;            } else {                   res[i] = preSum[sub[i] + 1];            }        }                return res;    }}

时空复杂度 O ( l A ) O(l_A) O(lA)

转载地址:http://mgcs.baihongyu.com/

你可能感兴趣的文章
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>
MySQL DBA 进阶知识详解
查看>>
Mura CMS processAsyncObject SQL注入漏洞复现(CVE-2024-32640)
查看>>
Mysql DBA 高级运维学习之路-DQL语句之select知识讲解
查看>>
mysql deadlock found when trying to get lock暴力解决
查看>>
MuseTalk如何生成高质量视频(使用技巧)
查看>>
mutiplemap 总结
查看>>
MySQL DELETE 表别名问题
查看>>
MySQL Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>
MySQL FEDERATED 提示
查看>>
mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
查看>>
Mysql group by
查看>>
MySQL I 有福啦,窗口函数大大提高了取数的效率!
查看>>
mysql id自动增长 初始值 Mysql重置auto_increment初始值
查看>>
MySQL in 太多过慢的 3 种解决方案
查看>>
MySQL InnoDB 三大文件日志,看完秒懂
查看>>
Mysql InnoDB 数据更新导致锁表
查看>>