三个抽象建模问题:
- 选择合理数据结构
- 分析模型中内在规律
面试题43:n个骰子点数
面试题44:扑克牌的顺子
http://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4?tpId=13&tqId=11198&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
class Solution { public: bool IsContinuous( vector<int> numbers ) { int len = numbers.size(); sort(numbers.begin(),numbers.end()); if(len <= 0) return false; int zero_count = 0; int gap_count = 0; for(int i = 0; i < len; i++) { if(numbers[i] == 0) zero_count++; else if( i + 1 < len) { if(numbers[i] == numbers[i+1]) return false; else gap_count += numbers[i+1] - numbers[i] - 1; } } if(gap_count > zero_count) return false; else return true; } };
面试题45:圆圈中最后剩下的数字
用list当作环形链表,当iterator遍历到end,设为begin
注意迭代器不能用四则运算,只能用自增自减,故在第22行用++,然后在26行要还原
1 int LastRemaining_Solution1(unsigned int n, unsigned int m) 2 { 3 if(n < 1 || m < 1) 4 return -1; 5 6 unsigned int i = 0; 7 8 list<int> numbers; 9 for(i = 0; i < n; ++ i) 10 numbers.push_back(i); 11 12 list<int>::iterator current = numbers.begin(); 13 while(numbers.size() > 1) 14 { 15 for(int i = 1; i < m; ++ i) 16 { 17 current ++; 18 if(current == numbers.end()) 19 current = numbers.begin(); 20 } 21 22 list<int>::iterator next = ++ current; 23 if(next == numbers.end()) 24 next = numbers.begin(); 25 26 -- current; 27 numbers.erase(current); 28 current = next; 29 } 30 31 return *(current); 32 }