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

Python - Algorithm #2

hkl22 2024. 6. 10. 10:40

Python Algorithm

LeetCode

347. Top K Frequent Elements

  • Given an integer array [nums] and an integer k, return the k most frequent elements. You may return the answer in any order.
  • Constraints:
    • 1 ≤ nums.length ≤ 10⁵
    • -10 ≤ nums[i] ≤ 10
    • k is in the range [1, the number of unique elements in the array].
    • It is guaranteed that the answer is unique.
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        answer = []
        # 1. nums 배열에 등장한 횟수 집계
        nums_dict = {}
        for num in nums:
            if num not in nums_dict:
                nums_dict[num] = 0
            nums_dict[num] += 1
        # 2. 많이 등장한 횟수별로 정렬
        sorted_keys = sorted(nums_dict, key=lambda x: nums_dict[x], reverse=True)
        # 3. sorted_keys에서 k개만큼 answer에 append
        for i in range(k):
            answer.append(sorted_keys[i])
        return answer
from collections import Counter

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
    	# 1. nums 배열에 등장한 횟수 집계
        nums_counter = Counter(nums)
        # 2. 많이 등장한 횟수로 정렬해서 앞에서부터 k개 리턴해주기
        return [x[0] for x in nums_counter.most_common()[:k]]
from collections import Counter

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        answer = []
        num_dict = Counter(nums)
        count = sorted(num_dict.items(), key=lambda x: x[1], reverse=True)
        for i in range(k):
            answer.append(count[i][0])
        return answer
  • Counter( ) : 주어진 객체의 요소를 키, 요소의 개수를 값으로 가지는 딕셔너리 생성
    • from collections import Counter
  • Counter( ).most_common(x) : 최빈값 x개 반환

2011. Final Value of Variable After Performing Operations

  • There is a programming language with only four operations and one variable X:
    • ++X and X++ increments the value of the variable X by 1.
    • --X and X-- decrements the value of the variable X by 1.
  • Initially, the value of X is 0.
  • Given an array of strings [operations] containing a list of operations, return the final value of X after performing all the operations.
  • Constraints:
    • 1 ≤ operations.length ≤ 100
    • operations[i] will be either "++X", "X++", "--X", or "X--".
class Solution:
    def finalValueAfterOperations(self, operations: List[str]) -> int:
        answer = 0
        for operation in operations:
            # X++ 혹은 ++X일 때는 +1
            # 아니면 -1
            if operation == "++X" or operation == "X++":
                answer += 1
            else:
                answer -= 1
        return answer
class Solution:
    def finalValueAfterOperations(self, operations: List[str]) -> int:
        answer = 0
        for i in operations:
            if "+" in i:
                answer += 1
            else:
                answer -= 1
        return answer

https://leetcode.com/problems/top-k-frequent-elements/

https://leetcode.com/problems/final-value-of-variable-after-performing-operations/

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

Python - Algorithm #6  (0) 2024.06.18
Python - Algorithm #5  (0) 2024.06.17
Python - Algorithm #4  (0) 2024.06.12
Python - Algorithm #3  (0) 2024.06.11
Python - Algorithm #1  (0) 2024.06.07