Skip to content

Commit f2958ee

Browse files
author
0x01f7
committed
solve: Perfect Squares
1 parent 11b3a2a commit f2958ee

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
| 282 | [Expression Add Operators][p282] | [Ruby][s282] | Hard |
2121
| 281 | [Zigzag Iterator][p281] | :lock: | Medium |
2222
| 280 | [Wiggle Sort][p280] | :lock: | Medium |
23-
| 279 | [Perfect Squares][p279] | | Medium |
23+
| 279 | [Perfect Squares][p279] | [Ruby][s279] | Medium |
2424
| 278 | [First Bad Version][p278] | [Ruby][s278] | Easy |
2525
| 277 | [Find the Celebrity][p277] | :lock: | Medium |
2626
| 276 | [Paint Fence][p276] | :lock: | Easy |

algorithms/perfect_squares.rb

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# https://leetcode.com/problems/perfect-squares/
2+
#
3+
# Given a positive integer n, find the least number of perfect square
4+
# numbers (for example, 1, 4, 9, 16, ...) which sum to n.
5+
#
6+
# For example,
7+
#
8+
# given n = 12, return 3 because 12 = 4 + 4 + 4;
9+
# given n = 13, return 2 because 13 = 4 + 9.
10+
11+
12+
# @param {Integer} n
13+
# @return {Integer}
14+
def num_squares(n)
15+
s = Math.sqrt(n).truncate
16+
return 1 if n == s * s
17+
18+
v = Array(1..s).map { |num| num * num }
19+
q, l = [n], 1
20+
21+
while true
22+
newq = []
23+
24+
q.each do |n1|
25+
v.each do |n2|
26+
case n1 <=> n2
27+
when 1; newq << n1 - n2
28+
when 0; return l
29+
when -1; break
30+
end
31+
end
32+
end
33+
34+
q, l = newq.uniq, l + 1
35+
end
36+
end

0 commit comments

Comments
 (0)