###不给自己任何借口
今日题目:
1、Ransom Note ; tag:字符串
2、在旋转有序数组中查找最小元素II tag:数组|二分
今日摘录:
草在结它的种子,风在摇它的叶子。我们站着,不说话,就十分美好。
——顾城《门前》
383. Ransom Note | Difficulty: Easy
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
tag:字符串
题意:判断一个ransom字符串否由magazines中的字符串组成,magazines中的每个字母只能用一次。
思路:用一个vector模拟hash_map就可以了,统计magazines中的字母出现次数,同时减去ransom中每个字母出现的次数,最后判断计数数组中的字母出现的次数有没有负数即可。
1、
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int>cnt(26,0);
for(int i=0;i<ransomNote.size();i++)
cnt[ransomNote[i]-'a'+0]--;
for(int i=0;i<magazine.size();i++)
cnt[magazine[i]-'a'+0]++;
for(int i=0;i<26;i++)
{
if(cnt[i]<0) return false;
}
return true;
}
};
结果:32ms
154. Find Minimum in Rotated Sorted Array II | Difficulty: Hard
Follow up for “Find Minimum in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array may contain duplicates.
tag:数组|二分查找
题意:在一个旋转数组中查找最小元素
思路:不断通过和最右元素进行比较,主要思考清楚nums[mid]与nums[right]相等情况下如何处理。
class Solution {
public:
int findMin(vector<int>& nums) {
int left = 0,right=nums.size()-1;
while(left<right)
{
// if(nums[left]<nums[right]) return nums[left];
int mid = left+(right-left)/2;
if(nums[mid]>nums[right]) left = mid+1;
else if (nums[mid] < nums[right]) right = mid;
else right--;
}
return nums[left];
}
};
结果:8ms