leecode 解题总结:275. H-Index II

来源:互联网 发布:stcisp软件下载 编辑:程序博客网 时间:2024/06/15 23:31
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题:Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?分析:题目给定了是升序,问如何进行优化。之前就是先排序。均篇引用次数>=h的至少有h篇,引用次数>=篇数从后向前:    nums[i] >= n - i就继续寻找直到找到不满足,上一次记录的值即为所求期望运行时间为O(logN),如果采用二分法:对于midnums[mid] < n - mid:说明mid不可能,low = mid + 1nums[mid] >= n - mid:           如果有:nums[mid-1] < n - (mid-1),则篇数size - mid即为所求   否则:当前位置不可能,high=mid-1输入:5(数组元素个数)0 1 3 5 61100输出:31关键:1 均篇引用次数>=h的至少有h篇,引用次数>=篇数从后向前:    nums[i] >= n - i就继续寻找直到找到不满足,上一次记录的值即为所求期望运行时间为O(logN),如果采用二分法:对于midnums[mid] < n - mid:说明mid不可能,low = mid + 1nums[mid] >= n - mid:           如果有:nums[mid-1] < n - (mid-1),则篇数size - mid即为所求   否则:当前位置不可能,high=mid-1*/class Solution {public:    int hIndex(vector<int>& citations) {if(citations.empty()){return 0;}int size = citations.size();int low = 0;int high = size - 1;int mid;while(low < high){mid = low + (high - low) / 2;if(citations.at(mid) < size - mid){low = mid + 1;}else{//找到了if(mid - 1 >= 0 && citations.at(mid-1) < size - (mid - 1)){return (size - mid);}else{high = mid - 1;}}}//如果low = high,if(citations.at(low) >= size - low){return (size - low);}else{return 0;}    }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } int answer = solution.hIndex(nums); cout << answer << endl; }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击