概要
プログラミング初心者でWebアプリケーションを制作していますが、
それだけではプログラミングの知識が浅いためLeetcodeで勉強をしました!
何問か解きましたが、勉強になったことが多いので備忘録として残しておこうと思います!
もっと綺麗な書き方あるよーって教えてくれる方がいたら是非コメントにお願いします!
(※解いた順なので、番号は前後します。)
(※他の方の解答を参考にした問題もあります。)
1672. Richest Customer Wealth
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the ith customer has in the jth bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
Example:
Input: accounts = [[1,2,3],[3,2,1]]
Output: 6
Explanation:
1st customer has wealth = 1 + 2 + 3 = 6
2nd customer has wealth = 3 + 2 + 1 = 6
Both customers are considered the richest with a wealth of 6 each, so return 6.
解答
def maximum_wealth(accounts)
accounts.map(&:sum).max
end
学んだこと
-
.map(&:メソッド名)
要素1つ1つに(&:メソッド名)
で与えられたメソッドを呼ぶ
ここではacconuntsの要素(Exampleだと[1,2,3]
と[3,2,1]
それぞれにsumが呼び出されている
accounts.map(&:sum) #=> [6,6]
-
max
配列の中の最大値を持つ要素を取得することができるメソッド
[6, 6].max #=> 6
[5, 6, 2].max #=> 6
[5, 6, 2, 4, 8, 4].max(3) #=> [8, 6, 5]
1470. Shuffle the Array
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Constraints:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
解答
def shuffle(nums, n)
ans = []
n.times do |i|
ans.push nums[i] #ans << nums[i]でも同じ結果
ans.push nums[i+n] #i番目にnを足すことでynの値を抜き出せる
end
ans
end
-
push
オブジェクト.push(“要素”)で配列の末尾に要素を追加できる
<<
でも同じ結果が得られる
771. Jewels and Stones
You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
解答
def num_jewels_in_stones(jewels, stones)
cnt = 0
jewels.split(//).each do |j|
cnt += stones.count(j)
end
cnt
end
-
split(//)
文字列を分割して配列にするメソッド
任意の文字や正規表現で分割する場合は第一引数で指定する
//
は文字列全体を 1 文字ずつに分割
文字列.split(区切り文字)
文字列.split(正規表現)
-
count
countの引数に指定した要素と一致するものを数える
'abc'.count('c') # => 1
'123456789'.count('2378') # => 4
1773. Count Items Matching a Rule
You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.
The ith item is said to match the rule if one of the following is true:
ruleKey == "type" and ruleValue == typei.
ruleKey == "color" and ruleValue == colori.
ruleKey == "name" and ruleValue == namei.
Return the number of items that match the given rule.
Example:
Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].
解答
def count_matches(items, rule_key, rule_value)
cnt = 0
items.each do |i|
if rule_key == "type" && i[0] == rule_value
cnt += 1
elsif rule_key == "color" && i[1] == rule_value
cnt += 1
elsif rule_key == "name" && i[2] == rule_value
cnt += 1
end
end
cnt
end
1365. How Many Numbers Are Smaller Than the Current Number
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
解答
def smaller_numbers_than_current(nums)
nums.map do |n|
cnt = 0
nums.each do |x|
cnt += 1 if n > x
end
cnt
end
end
-
each do
とmap do
の違い
-
each
繰り返し処理
-
mach
結果を配列で返す
-
array = [1, 2, 3, 4]
array.each do |a|
puts a * 2
end
2
4
6
8
=> [1, 2, 3, 4]
array = [1, 2, 3, 4]
ans = array.map do |a|
a * 2
end
=> [2, 4, 6, 8]
#上記をeachで書き換えると
array = [1, 2, 3, 4]
ans = []
array.each do |a|
ans << a * 2
end
=> [1, 2, 3, 4]
result #=> [2, 4, 6, 8]
1342. Number of Steps to Reduce a Number to Zero
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Example:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
解答
def number_of_steps (num)
cnt = 0
while num > 0 do
if num.even?
num = num / 2
cnt += 1
else
num = num - 1
cnt += 1
end
end
cnt
end
-
even?
偶数の場合→true
奇数の場合→false
(奇数か確かめたい場合はodd?
)
1528. Shuffle String
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
解答
def restore_string(s, indices)
ans = []
indices.each_with_index do |n, i|
ans[n] = s[i]
end
ans.join
end
-
join
配列を連結させ、1つの文字列にする
array = ["foo", "bar"]
array.join
=> "foobar"
1281. Subtract the Product and Sum of Digits of an Integer
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example :
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
解答
def subtract_product_and_sum(n)
arr = n.to_s.chars.map(&:to_i)
arr.inject(:*) - arr.sum
end
-
to_s
文字列以外のオブジェクトを文字列に変換するメソッド
n = 234
n.to_s
=> "234"
-
chars
文字列の各文字を文字列の配列で返す
n.to_s.chars
=> ["2", "3", "4"]
-
to_i
文字列を整数に変換
配列ひとつひとつに適用したいので、mapを用いる
n.to_s.chars.map(&:to_i)
=> [2, 3, 4]
最初、ここまでの作業をsplit(//)で分割しようとしていました。。
splitは文字列を分割できるだけなので、integerには使えません
-
inject(:*)
injectはブロックを使用して、繰り返し計算するメソッド
n.inject(:*)
=> 24
-
sum
inject(:+)と書いても良いが、sumの方が早いらしい。
inject(:*)の書き換えは見つからなかったので、知っている方がいたら教えてください・・
n.sum
=> 9
#最後に
まだまだLeetcodeは始めたばかりなので、どんどん解いてアップしていきたいと思います!
誰かのお役に立てたら嬉しいです:)