Torihaji's Growth Diary

Little by little, no hurry.

LeetCode生活9日目

はじめに

ついに前回でNeetCodeのRoadMapの最初が全て終わったので

今日はその問題を解き直してみることにする。

今日は初級全てにしよう。

Contains Duplicate

Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.

数字の配列が与えられるので要素に重複があればtrueを、それ以外はfalseを返せ

def contains_duplicate(nums)
    nums.sort.uniq != nums.sort
end

これも正解。ただ遅かったので、別のないか思い出す。

# @param {Integer[]} nums
# @return {Boolean}
def contains_duplicate(nums)
    hash = {}
    nums.each do |num|
        return true if hash[num]
        hash[num] ||= true
    end
    false
end

これでもまだ遅い。

あ、そうだこれだ。

def contains_duplicate(nums)
    nums.length != nums.uniq.length    
end

次。

Valid Anagram

Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.

文字列s,tが与えられる。一方が片方のアナグラムである時trueを、そうでない時はfalseを返せ

文字列にcharsすると文字の配列として返してくれる。覚えててよかった。

def is_anagram(s, t)
    s.chars.sort == t.chars.sort
end

これでも遅いのか。

そういえばこれもあったらしい。また忘れてる。

def is_anagram(s, t)
    return false if s.length != t.length
    s.chars.tally == t.chars.tally
end

次。

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

数字の配列とターゲットとなる数字が与えられる。

配列内の隣り合う2つの数字を足してターゲットの数字と等しくなる時、その2つの数字の配列内でのindexを配列にして返せ。

なお返す場合は順不同。

# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
    nums.each_with_index do |num, i|
        ((i + 1)...nums.length).each do |j|
            return [i , j] if target == num + nums[j]
        end
    end
    false
end

最強に遅い。

そういえば補数使うやり方あった。

# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
    hash = {}
    nums.each_with_index do |num, index|
        complement = target - num
        return [index, hash[complement]] if hash.has_key?(complement)
        hash[num] = index
    end
end

よーこんなの思いつく。

終わりに

意外と頭使う。

頭が疲れた。

まだまだや。