leetcode.com/problems/number-of-good-pairs/

 

Number of Good Pairs - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

javascript

/**
 * @param {number[]} nums
 * @return {number} 
 */
const numIdenticalPairs = (nums) => {
  const pairs = {}
  for (let i = 0; i < nums.length; i++) {
    pairs[nums[i]] ? pairs[nums[i]] += 1 : pairs[nums[i]] = 1
  }
  let numGoodPairs = 0
  const pairNums = Object.values(pairs)
  for (let i = 0; i < pairNums.length; i++) {
    numGoodPairs += (pairNums[i] * (pairNums[i] - 1)) / 2
  }
  return numGoodPairs
}

typescript

interface Pairs {
  [key: string]: number
}

const numIdenticalPairsTS = (nums: number[]): number => {
  const pairs: Pairs = {}
  for (let i = 0; i < nums.length; i++) {
    pairs[nums[i]] ? pairs[nums[i]] += 1 : pairs[nums[i]] = 1
  }
  let numGoodPairs: number = 0
  const pairNums = Object.keys(pairs)
  for (let i = 0; i < pairNums.length; i++) {
    numGoodPairs += (pairs[pairNums[i]] * (pairs[pairNums[i]] - 1)) / 2
  }
  return numGoodPairs
}

golang

func numIdenticalPairs(nums []int) int {
	goodPairs := 0
	pairs := make([]int, 101)
	for _, num := range nums {
		pairs[num]++
	}
	for _, pairsNum := range pairs {
		if pairsNum > 1 {
			goodPairs += pairsNum * (pairsNum - 1) / 2
		}
	}
	return goodPairs
}

'코딩 테스트 > LeetCode' 카테고리의 다른 글

Easy) 1108. Defanging an IP Address  (0) 2020.09.15
Easy) 771. Jewels and Stones  (0) 2020.09.15
Easy) Shuffle the Array  (0) 2020.09.13
Easy) Kids With the Greatest Number of Candies  (0) 2020.09.13
Easy. Running Sum of 1d Array  (0) 2020.07.02

+ Recent posts