0%

面试题 03.01. 三合一

面试题 03.01. 三合一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class TripleInOne {
public:
TripleInOne(int stackSize) : stacks(new int[stackSize * 3 + 3]), top1(0), top2(stackSize + 1), top3((stackSize << 1) + 2), stackSize(stackSize) {

}

void push(int stackNum, int value) {
switch(stackNum)
{
case 0 :
if(top1 == stackSize)
return;
stacks[++top1] = value;
break;
case 1:
if(top2 == (stackSize << 1) + 1)
return;
stacks[++top2] = value;
break;
case 2:
if(top3 == stackSize * 3 + 2)
return;
stacks[++top3] = value;
break;
}
}

int pop(int stackNum) {
if(isEmpty(stackNum))
return -1;
switch(stackNum)
{
case 0 :
return stacks[top1--];
case 1:
return stacks[top2--];
case 2:
return stacks[top3--];
}
return -1;
}

int peek(int stackNum) {
if(isEmpty(stackNum))
return -1;
switch(stackNum)
{
case 0 :
return stacks[top1];
case 1:
return stacks[top2];
case 2:
return stacks[top3];
}
return -1;
}

bool isEmpty(int stackNum) {
switch(stackNum)
{
case 0 :
return top1 == 0;
case 1:
return top2 == stackSize + 1;
case 2:
return top3 == (stackSize << 1) + 2;
}
return false;
}
private:
int* stacks;
int stackSize;
int top1;
int top2;
int top3;
};

/**
* Your TripleInOne object will be instantiated and called as such:
* TripleInOne* obj = new TripleInOne(stackSize);
* obj->push(stackNum,value);
* int param_2 = obj->pop(stackNum);
* int param_3 = obj->peek(stackNum);
* bool param_4 = obj->isEmpty(stackNum);
*/

review

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class TripleInOne {
public:
TripleInOne(int stackSize) : sz(stackSize) {
stack.resize(stackSize * 3);
begin[0] = 0;
begin[1] = sz;
begin[2] = sz << 1;
}

void push(int stackNum, int value) {
if(begin[stackNum] != sz * stackNum + sz)
stack[begin[stackNum]++] = value;
}

int pop(int stackNum) {
if(isEmpty(stackNum))
return -1;
return stack[--begin[stackNum]];
}

int peek(int stackNum) {
if(isEmpty(stackNum))
return -1;
return stack[begin[stackNum] - 1];
}

bool isEmpty(int stackNum) {
return begin[stackNum] == stackNum * sz;
}
private:
vector<int> stack;
int sz;
int begin[3];
};

/**
* Your TripleInOne object will be instantiated and called as such:
* TripleInOne* obj = new TripleInOne(stackSize);
* obj->push(stackNum,value);
* int param_2 = obj->pop(stackNum);
* int param_3 = obj->peek(stackNum);
* bool param_4 = obj->isEmpty(stackNum);
*/