TheAlgorithms-Ruby/data_structures/arrays/good_pairs.rb

42 lines
818 B
Ruby
Raw Normal View History

2021-04-26 23:03:15 +02:00
# Challenge name: Number of good pairs
#
# Given an array of integers nums.
# A pair (i,j) is called good if nums[i] == nums[j] and i < j.
# Return the number of good pairs.
#
# @param {Integer[]} nums
# @return {Integer}
#
2021-05-08 01:37:58 +02:00
#
# Approach 1: Brute Force
#
# Time Complexity: O(n^2)
#
2021-04-26 23:03:15 +02:00
def num_identical_pairs(nums)
2021-05-08 01:37:58 +02:00
count = 0
nums.each_with_index do |num, i|
target = num
nums.each_with_index do |num, j|
next if i >= j
2021-09-03 22:24:58 +02:00
count += 1 if num == target
2021-05-08 01:37:58 +02:00
end
end
count
2021-04-26 23:03:15 +02:00
end
2021-05-08 01:37:58 +02:00
2021-04-26 23:03:15 +02:00
nums = [1, 2, 3, 1, 1, 3]
puts(num_identical_pairs(nums))
# Output: 4
# Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
2021-05-08 01:37:58 +02:00
2021-04-26 23:03:15 +02:00
nums = [1, 1, 1, 1]
puts(num_identical_pairs(nums))
# Output: 6
# Explanation: Each pair in the array are good.
2021-05-08 01:37:58 +02:00
2021-05-12 17:37:08 +02:00
nums = [1, 2, 3]
puts(num_identical_pairs(nums))
# Output: 0