面试题 02.07. 链表相交
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode*p=headA,*q=headB;
while(p!=q)
{
p=p==NULL?headB:p->next;
q=q==NULL?headA:q->next;
}
return p;
}
};
面试题 02.08. 环路检测
快慢指针
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode*slow=head,*fast=head;
while(fast!=NULL&&fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
break;
}
}
//错误检查 没有回路
if(fast==NULL||fast->next==NULL)
return NULL;
/*将slow指向首部,fast指向碰撞处,两者距离环路
*起始处k步,若两者以相同速度移动,则必定会在环
*路起始处碰在一起*/
slow=head;
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
return fast;
}
};
面试题 03.01. 三合一
将一个数组分为三段,每段对应一个栈,每段第一个位置存储当前栈中元素个数。分配数组大小时,每个栈多分配一个空间用于存储栈元素个数。
class TripleInOne {
public:
vector<int>v;
int size;
TripleInOne(int stackSize) {
size=stackSize;
v.resize(3*stackSize+3);
}
void push(int stackNum, int value) {
int start=stackNum*(size+1);
if(v[start]<size) //第一个存储栈元素个数
{
int i=v[start];
v[start]=i+1;
v[start+i+1]=value;
}
}
int pop(int stackNum) {
int start=stackNum*(size+1);
if(v[start]>0)
{
int i=v[start];
v[start]=i-1;
return v[start+i];
}
return -1;
}
int peek(int stackNum) {
int start=stackNum*(size+1);
if(v[start]>0)
{
int i=v[start];
return v[start+i];
}
return -1;
}
bool isEmpty(int stackNum) {
int start=stackNum*(size+1);
if(v[start]==0)
return true;
else return false;
}
};
面试题 03.02. 栈的最小值
class MinStack {
public:
stack<int>s1;
stack<int>s2;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(s1.empty())
{
s1.push(x);
s2.push(x);
}
else
{
s1.push(x);
s2.push(min(s2.top(),x));
}
}
void pop() {
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};
面试题 03.03. 堆盘子
class StackOfPlates {
public:
vector<stack<int>>s;
int size1;
StackOfPlates(int cap) {
size1=cap;
}
void push(int val) {
if(size1==0) return;
if(s.size()==0||s[s.size()-1].size()==size1)
{
stack<int>n;
n.push(val);
s.push_back(n);
}
else
s[s.size()-1].push(val);
}
int pop() {
if(s.size()==0)
return -1;
int res=s[s.size()-1].top();
s[s.size()-1].pop();
if(s[s.size()-1].empty())
{
s.pop_back();
}
return res;
}
int popAt(int index) {
if(s.size()==0||index<0||index>=s.size()) return -1;
int res=s[index].top();
s[index].pop();
if(s[index].empty())
{
s.erase(s.begin()+index);
}
return res;
}
};