LeetCode 题解工作台
求解方程
求解一个给定的方程,将 x 以字符串 "x=#value" 的形式返回。该方程仅包含 '+' , '-' 操作,变量 x 和其对应系数。 如果方程没有解或存在的解不为整数,请返回 "No solution" 。如果方程有无限解,则返回 “Infinite solutions” 。 题目保证,如果方程…
3
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数学·string
答案摘要
将方程 按照等号 “=” 切分为左右两个式子,分别算出左右两个式子中 "x" 的系数 ,以及常数的值 。 那么方程转换为等式 $x_1 \times x + y_1 = x_2 \times x + y_2$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
求解一个给定的方程,将x以字符串 "x=#value" 的形式返回。该方程仅包含 '+' , '-' 操作,变量 x 和其对应系数。
如果方程没有解或存在的解不为整数,请返回 "No solution" 。如果方程有无限解,则返回 “Infinite solutions” 。
题目保证,如果方程中只有一个解,则 'x' 的值是一个整数。
示例 1:
输入: equation = "x+5-3+x=6+x-2" 输出: "x=2"
示例 2:
输入: equation = "x=x" 输出: "Infinite solutions"
示例 3:
输入: equation = "2x=x" 输出: "x=0"
提示:
3 <= equation.length <= 1000equation只有一个'='.- 方程由绝对值在
[0, 100]范围内且无任何前导零的整数和变量'x'组成。
解题思路
方法一:数学
将方程 按照等号 “=” 切分为左右两个式子,分别算出左右两个式子中 "x" 的系数 ,以及常数的值 。
那么方程转换为等式 。
- 当 :若 ,方程无解;若 ,方程有无限解。
- 当 :方程有唯一解 。
相似题目:
class Solution:
def solveEquation(self, equation: str) -> str:
def f(s):
x = y = 0
if s[0] != '-':
s = '+' + s
i, n = 0, len(s)
while i < n:
sign = 1 if s[i] == '+' else -1
i += 1
j = i
while j < n and s[j] not in '+-':
j += 1
v = s[i:j]
if v[-1] == 'x':
x += sign * (int(v[:-1]) if len(v) > 1 else 1)
else:
y += sign * int(v)
i = j
return x, y
a, b = equation.split('=')
x1, y1 = f(a)
x2, y2 = f(b)
if x1 == x2:
return 'Infinite solutions' if y1 == y2 else 'No solution'
return f'x={(y2 - y1) // (x1 - x2)}'
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity depend on how you process the equation. Parsing the string and performing arithmetic operations both involve linear time complexity, O(n), where n is the length of the equation. Space complexity depends on how the equation is stored and split, typically O(n). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for candidates who can break down and parse the string effectively.
- question_mark
Evaluate how well they handle edge cases, such as infinite solutions or no solutions.
- question_mark
Assess if they can balance the equation systematically and solve for 'x' without skipping steps.
常见陷阱
外企场景- error
Overcomplicating the parsing process, leading to errors when extracting coefficients or constants.
- error
Failing to account for edge cases, such as when the equation simplifies to 'x=x' (infinite solutions).
- error
Mismanaging signs during the balancing step, which could lead to incorrect values for 'x'.
进阶变体
外企场景- arrow_right_alt
Equations with only addition or subtraction operations.
- arrow_right_alt
Handling more complex terms such as fractions or higher powers of 'x'.
- arrow_right_alt
Expanding the problem to handle multiple variables or more complicated expressions.