leetcode题解——hot100easy题
枚举
LCP33.蓄水
找到省级水桶的蓄水操作的制约关系,蓄水的次数有上限,可以枚举每一次蓄水,从而计算出相应的升级次数。需要注意边界。
class Solution {
public:
int storeWater(vector<int>& bucket, vector<int>& vat) {
int Maxk=*max_element(vat.begin(),vat.end());
if(Maxk==0)return 0;
int res=1000000;
for(int i=1;i<=Maxk;i++){
int up=0;
for(int j=0;j<vat.size();j++){
up+=max(vat[j]/i+(vat[j]%i!=0)-bucket[j],0);
}
res=min(res,i+up);
}
return res;
}
};
数据结构:栈、哈希、链表
LCP1.两数之和
和为target的两个数为一对,使用hashmap,存放已遍历的nums[i]和其下标。遍历时,判断当前数在hashmap中是否有配对,如果有则返回下标,如果没有则加入到hashmap中。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
for(int i=0;i<nums.size();i++){
auto it=hash.find(target-nums[i]);
if(it!=hash.end()){
return {
it->second,i};
}
hash[nums[i]]=i;
}
return {
};
}
};
LCP20.有效的括号
使用栈来判断是否匹配,栈底存放’#'方便遍历进行比较。ASCII码相差1或者2可作为判断条件。
class Solution {
public:
bool isValid(string s) {
stack<char> st;
st.push('#');
for(int i=0;i<s.length();i++){
if(s[i]-st.top()==1||s[i]-st.top()==2){
st.pop();
}
else
st.push(s[i]);
}
if(st.top()=='#')return true;
else return false;
}
};
LCP141.环形链表
链表经典的双指针算法。
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL