141.环形链表
题目链接
显然的做法是用unordered_map,节约空间可以用快慢指针。
class Solution {
public:
bool hasCycle(ListNode *head) {
ios::sync_with_stdio(false);
if(!(head && head -> next))return false;
ListNode *p1 = head -> next;
ListNode *p2 = p1 -> next;
while(p1 && p2){
if(p1 == p2)return true;
p1 = p1 -> next;
p2 = p2 -> next;
if(p2)p2 = p2 -> next;
}
return false;
}
};
155.最小栈
题目链接
class MinStack {
public:
/** initialize your data structure here. */
deque<int>mn;
deque<int>ans;
MinStack() {
}
void push(int x) {
ans.emplace_back(x);
if(mn.empty()||x <= mn.back())mn.emplace_back(x);
}
void pop() {
if(ans.back()==mn.back())mn.pop_back();
ans.pop_back();
}
int top() {
return ans.back();
}
int getMin() {
return mn.back();
}
};