Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6fbf025

Browse files
Add files via upload
1 parent 68afba7 commit 6fbf025

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// 根据题目说明,两者都是正数
2+
// 基本思路是使用广度优先搜索,但是很明显的超时了
3+
// 明显超时
4+
5+
class Solution
6+
{
7+
public:
8+
int brokenCalc(int start, int end)
9+
{
10+
if (start >= end)
11+
{
12+
return start - end;
13+
}
14+
15+
queue<int> memo;
16+
memo.push(start);
17+
18+
int layer = 0;
19+
while (!memo.empty())
20+
{
21+
for (int i = memo.size(); i > 0; --i)
22+
{
23+
int temp = memo.front();
24+
memo.pop();
25+
26+
if (temp == end)
27+
{
28+
return layer;
29+
}
30+
31+
if (temp > 1) memo.push(temp - 1);
32+
if (temp < end) memo.push(temp * 2);
33+
}
34+
++layer;
35+
}
36+
37+
return -1;
38+
}
39+
};
40+
41+
// 改成递归贪心
42+
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Broken Calculator.
43+
// Memory Usage: 8.2 MB, less than 80.00% of C++ online submissions for Broken Calculator.
44+
45+
class Solution
46+
{
47+
public:
48+
int brokenCalc(int start, int end)
49+
{
50+
if (start >= end)
51+
{
52+
return start - end;
53+
}
54+
55+
if (end % 2 == 0)
56+
{
57+
return brokenCalc(start, end / 2) + 1;
58+
}
59+
else
60+
{
61+
return brokenCalc(start, end + 1) + 1;
62+
}
63+
}
64+
};
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Runtime: 40 ms, faster than 27.06% of Python3 online submissions for Broken Calculator.
2+
# Memory Usage: 14 MB, less than 50.00% of Python3 online submissions for Broken Calculator.
3+
4+
class Solution:
5+
def brokenCalc(self, start: int, end: int) -> int:
6+
7+
if start >= end:
8+
return start - end
9+
10+
if end % 2 is 0:
11+
return self.brokenCalc(start, end // 2) + 1
12+
else:
13+
return self.brokenCalc(start, end + 1) + 1

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /