货拉拉的编程题主要考察的是算法和数据结构的应用能力,以下是针对你提到的一些题目的解答思路:
一面 编程题 :给定一个数字列表,用列表中的数字构建出一个最大的数。解题思路
这个问题可以转化为一个排序问题,但排序规则需要自定义。
具体规则是:比较两个数字时,较大的数字排在前面,如果数字相同,则按照它们在原列表中的顺序排列。
代码示例:
```cpp
include include include include std::string largestNumber(std::vector std::string result; std::sort(nums.begin(), nums.end(), [](int a, int b) { return std::to_string(a) + std::to_string(b) > std::to_string(b) + std::to_string(a); }); for (int num : nums) { result += std::to_string(num); } return result.empty() ? "0" : result; } int main() { std::vector std::cout << largestNumber(nums) << std::endl; // 输出 9530 return 0; } ``` 解题思路 使用两个栈分别存储数字和操作符。 遍历字符串,根据运算符的优先级进行计算。 操作符的优先级:乘除优先于加减。 代码示例: ```cpp include include include int calculate(const std::string& s) { std::stack std::stack int num = 0; char op = '+'; for (char c : s) { if (isdigit(c)) { num = num * 10 + (c - '0'); } if (!isdigit(c) && c != ' ' || ops.top() == '(') { if (op == '+') { nums.push(num); } else if (op == '-') { nums.push(-num); } else if (op == '*') { int prev = nums.top(); nums.pop(); nums.push(prev * num); } else if (op == '/') { int prev = nums.top(); nums.pop(); nums.push(prev / num); } op = c; num = 0; } } int result = 0; while (!nums.empty()) { result += nums.top(); nums.pop(); } return result; } int main() { std::string expression = "1+2-3*4/5"; std::cout << calculate(expression) << std::endl; // 输出 1 return 0; } ``` 建议 理解题目:仔细阅读题目,明确输入和输出的格式和要求。 选择合适的数据结构:根据题目特点选择合适的数据结构,如栈、队列、树等。 算法设计:设计高效的算法,考虑时间复杂度和空间复杂度。 代码实现:注意代码的可读性和健壮性,进行充分的测试。二面 编程题 :针对输入的字符串计算其最终表达式。