LeetCode 274. H-Index
int hIndex(vector& citations) {
sort(citations.begin(), citations.end());
reverse(citations.begin(), citations.end());
int n = citations.size(), index = 0;
for(int i = 0; i < n; i++)
if (citations[i] >= i + 1)
index = i + 1 > index ? i + 1 : index;
return index;
}
h-index的概念:"A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
思路:从高到低排序,寻找最后一个值大于等于下标(从1开始)的即可。
LeetCode 275. H-Index II
int hIndex(vector& citations) {
reverse(citations.begin(), citations.end());
int n = citations.size(), index = 0;
for(int i = 0; i < n; i++)
if (citations[i] >= i + 1)
index = i + 1 > index ? i + 1 : index;
return index;
}
思路:同上,不过这次不用自己排序 - 。-
LeetCode 217. Contains Duplicate
bool containsDuplicate(vector& nums) {
unordered_map m;
for(int i = 0; i < nums.size(); i++)
if(++m[nums[i]] > 1)
return true;
return false;
}
思路:判断是否有重复,计数器A上去就完事了qwq
bool containsDuplicate(vector& nums)
{
sort(begin(nums), end(nums));
return unique(begin(nums), end(nums)) != end(nums);
}
InversePalindrome 的骚操作
LeetCode 219. Contains Duplicate II
bool containsNearbyDuplicate(vector& nums, int k) {
unordered_map m;
for(int i = 0; i < nums.size(); i++)
if(m[nums[i]] == 0)
m[nums[i]] = i+1;
else if(i+1-m[nums[i]]<=k)
return true;
else
m[nums[i]] = i+1;
return false;
}
思路:老规矩计数器,第二个位置记录前一个相同的数的下标,比较就行了2333
LeetCode 220. Contains Duplicate III
bool cmp(const pair & x, const pair & y) {
if(x.first == y.first)
return x.second < y.second;
return x.first < y.first;
}
bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) {
vector > vec;
for(int i = 0; i < nums.size(); i++)
vec.push_back(make_pair(nums[i], i));
sort(vec.begin(), vec.end(), cmp);
long long fast = 1, slow = 0, n = nums.size();
while(fast < n) {
long long diff_t = vec[fast].first - vec[slow].first;
long long diff_k = abs(vec[fast].second - vec[slow].second);
if(diff_t <= t) {
if(diff_k <= k)
return true;
else
fast++;
}
else {
slow++;
if(fast == slow)
fast++;
}
}
return false;
}
思路:先将值与下标组成pair,按照值的大小排序,顺序查找,注意溢出即可。
lx223 的思路:AC O(N) solution in Java using buckets with explanation
LeetCode 55.Jump Game
bool canJump(vector& nums) {
if(nums.size() == 0 || nums.size() == 1) return true;
int reach = nums[0];
for(int i = 1; i < nums.size(); i++) {
if(reach < i) return false;
reach = max(reach, nums[i] + i);
}
return reach >= nums.size()-1;
}
或者:
bool canJump(vector& nums) {
int reach = 0, len = nums.size() - 1;
for(int i = 0; i < len && i <= reach; ++i)
reach = max(nums[i] + i, reach);
return reach >= len;
}
思路:贪心,取最大到达距离,最后判断是否能够到达。
LeetCode 45. Jump Game II
int jump(vector& nums) {
int step = 0, reach = 0, index = 0;
while(reach < nums.size() - 1) {
step++;
int tmp = reach;
while(index <= tmp) {
reach = max(reach, index + nums[index]);
index++;
}
}
return step;
}
思路:贪心,在每一步中寻找尽可能走得更远的位置。