LoginSignup
0
0

More than 3 years have passed since last update.

LeetCode - 21. Merge Two Sorted Lists

Last updated at Posted at 2020-01-25

ListNodeをつくる

配列からListNodeのテストデータを作る


# Definition for singly-linked list.
class ListNode
  attr_accessor :val, :next
  def initialize(val)
    @val = val
    @next = nil
  end
end

def create_list_node(array)
  array_of_list_nodes = array.map{|n|
    ListNode.new(n)
  }

  lns = ListNode.new(0)
  buf = lns
  array_of_list_nodes.each{|ln|
    lns.next = ln
    lns = lns.next
    #p lns
    #p buf
  }
  buf.next 
end

ln1 =  create_list_node([1,2,4])
ln2 =  create_list_node([1,3,4])

  • buf のところがポイント

ListNodeをマージする


def merge_two_lists(ln1, ln2)
  ln3 = ListNode.new(0)
  buf = ln3

  while ln1 && ln2
    if ln1.val <= ln2.val
      ln3.next = ln1
      ln1 = ln1.next
    else
      ln3.next = ln2
      ln2 = ln2.next
    end
    ln3 = ln3.next
  end

  ln3.next = ln1 || ln2 
  buf.next
end

  • buf のところがポイント
  • 条件式 ln1 && ln2はどちらかが nilfalse
  • buf は先頭ノードを仮に0で作ってるので、nextを返す

スコア


Runtime: 72 ms, faster than 10.21% of Ruby online submissions for Merge Two Sorted Lists.
Memory Usage: 9.6 MB, less than 100.00% of Ruby online submissions for Merge Two Sorted Lists.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0