Python Algorithm
LeetCode
2639. Find the Width of Columns of a Grid
- You are given a 0-indexed m x n integer matrix [grid]. The width of a column is the maximum length of its integers.
- For example, if grid = [[-10], [3], [12]], the width of the only column is 3 since -10 is of length 3.
- Return an integer array [ans] of size n where ans[i] is the width of the iᵗʰ column.
- The length of an integer x with len digits is equal to len if x is non-negative, and len + 1 otherwise.
- Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- -10⁹ ≤ grid[r][c] ≤ 10⁹
class Solution:
def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
answer = [0] * len(grid[0])
for i in range(len(grid)):
for j in range(len(grid[0])):
num_len = len(str(grid[i][j]))
answer[j] = max(answer[j], num_len)
return answer
class Solution:
def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
answer = []
for i in range(len(grid[0])):
length = 0
for j in range(len(grid)):
if len(str(grid[j][i])) > length:
length = len(str(grid[j][i]))
answer.append(length)
return answer
2404. Most Frequent Even Element
- Given an integer array nums, return the most frequent even element.
- If there is a tie, return the smallest one. If there is no such element, return -1.
- Constraints
- 1 ≤ nums.length ≤ 2000
- 0 ≤ nums[i] ≤ 10⁵
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
even_num = [x for x in nums if x % 2 == 0]
if not even_num:
return -1
c = Counter(even_num)
max_freq = max(list(c.values()))
# max_freq만큼 등장한 숫자들 찾아서 가장 작은 값을 리턴
candidates = [num for num, cnt in c.items() if cnt == max_freq]
return sorted(candidates)[0]
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
answer = []
c = Counter(nums)
c = dict(filter(lambda x: x[0] % 2 == 0, c.items()))
c = sorted(c.items(), key=lambda x: (-x[1], x[0]))
if len(c) >= 1:
return c[0][0]
else:
return -1
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
nums = [num for num in nums if num % 2 == 0]
if not nums:
return -1
c = Counter(nums)
c = sorted(c.items(), key=lambda x: (-x[1], x[0]))
return c[0][0]
https://leetcode.com/problems/find-the-width-of-columns-of-a-grid/
'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글
| Python - Algorithm #58 (0) | 2024.09.26 |
|---|---|
| Python - Algorithm #57 (0) | 2024.09.25 |
| Python - Algorithm #55 (0) | 2024.09.23 |
| Python - Algorithm #54 (0) | 2024.09.20 |
| Python - Algorithm #53 (0) | 2024.09.19 |