博客
关于我
【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/

你可能感兴趣的文章
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>
MySQL 索引的面试题总结
查看>>
mysql 索引类型以及创建
查看>>
MySQL 索引连环问题,你能答对几个?
查看>>
Mysql 索引问题集锦
查看>>
Mysql 纵表转换为横表
查看>>
mysql 编译安装 window篇
查看>>
mysql 网络目录_联机目录数据库
查看>>
MySQL 聚簇索引&&二级索引&&辅助索引
查看>>
Mysql 脏页 脏读 脏数据
查看>>
mysql 自增id和UUID做主键性能分析,及最优方案
查看>>
Mysql 自定义函数
查看>>
mysql 行转列 列转行
查看>>
Mysql 表分区
查看>>
mysql 表的操作
查看>>