Google Interview Report
- 0of 0 votes
AnswersWrite code to print out a binary tree so that each depth is printed on its own line. The spacing doesn't need to be correct, but the items within a depth must be in order and on a single line.
- Han April 09, 2009
1
/ \
2 3
/ \
4 5
\
7
1
2 3
4 5
7| Report Duplicate | Flag | PURGE
Google Software Engineer in Test Trees and Graphs - 0of 0 votes
Answersint getNthNonZeroElement(vector<int> & elements, int n) {
- Han April 09, 2009
vector<int>::iterator i;
int count;
for (i = elements.begin(); i < elements.end(); i++) {
if ((*i) != 0) {
if (count == n) {
return (*i);
}
count++;
}
}
return -1;
}
The above code should return the nth non-zero element. For example, given vector v = [0, 8, 6, 0, 9, 7,20], should return 9 if n pass-in is 3;
Question: optimizing it.
My answer:
int getNthNonZeroElement(vector<int> & elements, int n) {
vector<int>::iterator i;
for (i = elements.begin(); i < elements.end(); i++) {
n -= ((*i) != 0);
if (n == 0) return (*i);
}
return -1;
}
btw, the original question should init count = 0| Report Duplicate | Flag | PURGE
Google Software Engineer in Test Coding