지난 공부기록/알고리즘 풀이

Python - Algorithm #3

hkl22 2024. 6. 11. 14:43

Python Algorithm

LeetCode

2951. Find the Peaks

  • You are given a 0-indexed array [mountain]. Your task is to find all the peaks in the [mountain] array.
  • Return an array that consists of indices of peaks in the given array in any order.
  • Notes:
    • A peak is defined as an element that is strictly greater than its neighboring elements.
    • The first and last elements of the array are not a peak.
  • Constraints:
    • 3 mountain.length 100
    • 1 mountain[i]  100
class Solution:
    def findPeaks(self, mountain: List[int]) -> List[int]:
        answer = []
        for i in range(len(mountain)):
            # 첫 번째와 마지막 element 건너뛰기
            if i == 0 or i == len(mountain) - 1:
                continue
            # 왼쪽 값, 오른쪽 값 둘 다 한테 모두 큰 경우, answer에 i 추가
            if mountain[i] < mountain[i-1] and mountain[i] > mountain[i+1]:
                answer.append(i)
        return answer
class Solution:
    def findPeaks(self, mountain: List[int]) -> List[int]:
        answer = []
        for i in range(1, len(mountain)-1):
            if mountain[i-1] < mountain[i] and mountain[i] > mountain[i+1]:
                answer.append(i)
        return answer

3005. Count Elements With Maximum Frequency

  • You are given an array [nums] consisting of positive integers.
  • Return the total frequencies of elements in nums such that those elements all have the maximum frequency.
  • The frequency of an element is the number of occurrences of that element in the array.
  • Constraints:
    • 1 ≤ nums.length ≤ 100
    • 1 ≤ nums[i] ≤ 100
from collections import Counter

class Solution:
    def maxFrequencyElements(self, nums: List[int]) -> int:
        nums_counter = Counter(nums)
        answer = 0
        # 1. 가장 많이 등장한 횟수 m 구하기
        m = max(nums_counter.values())
        # 2. counter를 순회하면서 등장 횟수가 m인 숫자를 찾아서 answer에 더해주기
        for k, v in nums_counter.items():
            # v가 m과 같은지 비교, 같다면 answer에 v 더해주기
            if v == m:
                answer += v
        return answer
from collections import Counter

class Solution:
    def maxFrequencyElements(self, nums: List[int]) -> int:
        answer = 0
        nums_dict = Counter(nums)
        for i, j in nums_dict.items():
            if j == max(nums_dict.values()):
                answer += j
        return answer

https://leetcode.com/problems/find-the-peaks/

https://leetcode.com/problems/count-elements-with-maximum-frequency/

'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글

Python - Algorithm #6  (0) 2024.06.18
Python - Algorithm #5  (0) 2024.06.17
Python - Algorithm #4  (0) 2024.06.12
Python - Algorithm #2  (0) 2024.06.10
Python - Algorithm #1  (0) 2024.06.07