From 291b5be8094abb5c2d971d1421a5e7b56862e624 Mon Sep 17 00:00:00 2001 From: "Ahmed M. Abd EL-latif" Date: Fri, 10 Jun 2022 18:00:46 +0200 Subject: [PATCH] 70 && 83 && 88 --- Climbing_Stairs.rb | 37 ++++++++++++++++++++ Merge_Sorted_Array.rb | 24 +++++++++++++ Remove_Duplicates_from_Sorted_Linked_List.rb | 13 +++++++ 3 files changed, 74 insertions(+) create mode 100644 Climbing_Stairs.rb create mode 100644 Merge_Sorted_Array.rb create mode 100644 Remove_Duplicates_from_Sorted_Linked_List.rb diff --git a/Climbing_Stairs.rb b/Climbing_Stairs.rb new file mode 100644 index 0000000..985907b --- /dev/null +++ b/Climbing_Stairs.rb @@ -0,0 +1,37 @@ +# +# @lc app=leetcode id=70 lang=ruby +# +# [70] Climbing Stairs +# +# https://leetcode.com/problems/climbing-stairs/description/ +# +# You are climbing a stair case. It takes n steps to reach to the top. +# +# Each time you can either climb 1 or 2 steps. In how many distinct +# ways can you climb to the top? +# +# Note: Given n will be a positive integer. +# +# Example 1: +# +# Input: 2 +# Output: 2 +# Explanation: There are two ways to climb to the top. +# 1. 1 step + 1 step +# 2. 2 steps +# +# Example 2: +# +# Input: 3 +# Output: 3 +# Explanation: There are three ways to climb to the top. +# 1. 1 step + 1 step + 1 step +# 2. 1 step + 2 steps +# 3. 2 steps + 1 step + + +# @param {Integer} n +# @return {Integer} +def climb_stairs(n) + Hash.new { |h, k| h[k] = h[k-1] + h[k-2] }.merge({1=>1, 2=>2})[n] +end \ No newline at end of file diff --git a/Merge_Sorted_Array.rb b/Merge_Sorted_Array.rb new file mode 100644 index 0000000..ab61146 --- /dev/null +++ b/Merge_Sorted_Array.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums1 +# @param {Integer} m +# @param {Integer[]} nums2 +# @param {Integer} n +# @return {Void} Do not return anything, modify nums1 in-place instead. +def merge(nums1, m, nums2, n) + i, j, k = n - 1, m - 1, nums1.size - 1 + + while i >= 0 + if j < 0 + nums1[k] = nums2[i] + i -= 1 + elsif nums1[j] > nums2[i] + nums1[k] = nums1[j] + j -= 1 + else + nums1[k] = nums2[i] + i -= 1 + end + k -= 1 + end + + nums1 +end \ No newline at end of file diff --git a/Remove_Duplicates_from_Sorted_Linked_List.rb b/Remove_Duplicates_from_Sorted_Linked_List.rb new file mode 100644 index 0000000..1c7c7c9 --- /dev/null +++ b/Remove_Duplicates_from_Sorted_Linked_List.rb @@ -0,0 +1,13 @@ +def delete_duplicates(head) + cursor = head + + while cursor and cursor.next + if cursor.next.val == cursor.val + cursor.next = cursor.next.next + else + cursor = cursor.next + end + end + + head +end \ No newline at end of file