leetcode笔记:H-Index II
来源:互联网 发布:p站软件 编辑:程序博客网 时间:2024/06/05 14:19
一. 题目描述
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
二. 题目分析
该题与H-Index一题的要求基本一致,只是多提供了一个条件,即传入的数组本身已经是升序排列的,因此实际上操作会方便许多,也无需再使用辅助数组。该题仍然可以使用H-Index方法从后往前遍历数组,即可计算出h指数,算法复杂度为O(n)
,但更快的方法是使用二分查找,复杂度降为O(logn)
。
三. 示例代码
// 简单的从后往前遍历数组,较为耗时class Solution {public: int hIndex(vector<int>& citations) { if (citations.size() == 0) return 0; int result = 0; for (int i = citations.size() - 1; i >= 0; --i) { if (result >= citations[i]) return result; ++result; } return citations.size(); }};
// 二分查找,效率更快class Solution {public: int hIndex(vector<int>& citations) { int size = citations.size(); if (size == 0) return 0; int left = 0, right = size - 1; while (left < right){ int mid = left + (right - left) / 2; if (size - mid > citations[mid]) left = mid + 1; else right = mid; } return (size - right) < citations[right] ? (size - right) : citations[right]; }};
四. 小结
题目的提示略显多余。
4 0
- leetcode笔记:H-Index II
- Leetcode: H-Index II
- Leetcode: H-Index II
- [LeetCode]H-Index II
- H-Index II -- leetcode
- LeetCode H-Index II
- leetcode H-Index II
- [Leetcode]H-Index II
- [LeetCode] H-Index II
- LeetCode -- H-Index II
- [LeetCode]H-Index II
- LeetCode:H-Index II
- 【Leetcode】H-Index II
- Leetcode H-Index II
- leetcode:H-Index II
- LeetCode H-index and H-index II
- leetcode之H-index &&H-index II
- [leetcode] 275.H-Index II
- mongodb 常用查询语句整理
- hdu 2093 考试排名
- [ZJOI2014][JZOJ3617]力
- 多线程死锁问题
- Merkel Under Pressure After Migrant Influx
- leetcode笔记:H-Index II
- Future和FutureTask区别
- centos7下安装fastdfs
- 转场动画 学习
- 我的CentOS环境部署过程:从vmware安装到环境搭建
- qt 使用xlslib操作execl
- HTTP的GET请求中文乱码
- Linux编程中目录内容的读取(实现ls功能)
- iOS 真机 Could not launch "***"