Conversation
|
|
||
| class Solution: | ||
| def isPalindrome(self, s: str) -> bool: | ||
| if s is " ": |
There was a problem hiding this comment.
python에서 is의 경우 짧은 문자열일 경우에는 같은 객체로 취급하기때문에 equal이지만 긴 문자열일때는 ==를 사용해야 한다고 하네요. 몰랐던 사실이라 공유해봅니다!
There was a problem hiding this comment.
감사합니다~! 아직 python에 익숙하지 않아서 실수했습니다
There was a problem hiding this comment.
지금도 사실 짧은 문자열이라 사실 결과값은 같으니까 문제 없는 코드라고 생각됩니다!
| reg = "[^a-z0-9]" | ||
| converted_s = re.sub(reg, "", s.lower()) |
There was a problem hiding this comment.
regex가 간편해서 저도 사용하긴 했는데 사실 regex보단 내장함수들이 성능이 좋을거라 gpt한테 물어봤더니 이런 코드를 제안해주네요! (코드가 그렇게 가독성이 좋진 않은 것 같아서 좋은진 잘 모르겠습니다... ㅎ..)
class Solution:
def isPalindrome(self, s: str) -> bool:
# 문자열을 소문자로 변환하고 알파벳과 숫자만 남김
converted_s = ''.join(c for c in s.lower() if c.isalnum())
# 회문 여부 판단
return converted_s == converted_s[::-1]There was a problem hiding this comment.
코멘트 잘 봤어요!
말씀하신 대로 내장함수 기반 접근이 regex보다 성능상 유리할 것 같습니다😀
그리고 제너레이터 표현식을 사용하는 것도 효율성 면에서 좋은 것 같습니다.
약간의 가독성을 향상을 위해서 s.lower만 분리해서 적용해봤어요
leetcode-study/valid-palindrome/dusunax.py
Lines 25 to 26 in e6c66d5
| class Solution: | ||
| def topKFrequent(self, nums: List[int], k: int) -> List[int]: | ||
| frequency_map = Counter(nums) # TC: O(n), SC: O(n) | ||
| sorted_frequencies = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True) # TC: O(n log n), SC: O(n) | ||
|
|
||
| result = [] # SC: O(k) | ||
| for e in sorted_frequencies: # TC: O(k) | ||
| result.append(e[0]) | ||
|
|
||
| return result[0:k] |
There was a problem hiding this comment.
저도 이런식으로 풀었는데
기본적으로 보통 언어들에서는 Quick sort를 기반으로한 정렬을 하기 때문에 O(nlogn) 입니다.
Bucket sort를 이용하면 시간적으로 조금 더 효율적으로 풀 수 있을 것 같습니다!
제가 python을 잘 모르겠어서 js로 풀이 공유드립니다!
const input = [1, 1, 1, 2, 2, 3];
function topKFrequent(nums, k) {
const count = new Map();
nums.forEach((num) => {
count.set(num, (count.get(num) || 0) + 1);
}); // { 1 => 3, 2 => 2, 3 => 1 }
const frequent = Array.from({ length: nums.length + 1 }, () => []); // [[], [], [], [], ...] 처럼 0부터 nums.length까지 빈 배열을 생성
for (const [num, freq] of count) {
frequent[freq].push(num);
} // [[], [3], [2], [1], ...] 처럼 빈 배열에 빈도수에 해당하는 숫자를 넣음
const result = [];
// index가 빈도수, value가 숫자이기 때문에 뒤부터 돌아야 빈도수가 높은 숫자부터 result를 넣을 수 있다.
for (let i = frequent.length - 1; i >= 0; i--) {
// 빈도수가 높은 숫자부터 result에 넣음
for (const num of frequent[i]) {
result.push(num);
// k개만큼 result에 넣으면 종료
if (result.length === k) {
return result;
}
}
}
return result;
}
console.log(topKFrequent(input, 2));가독성은 좀 구리지만... 성능적으로는 아주 큰수로 갈때 이득을 볼 수 있습니다!
There was a problem hiding this comment.
파이썬 라이브러리와 문법은 정말.. 알고리즘 풀기에 행복한 수준이네요 ㅎㅎ
답안 제출 문제
체크 리스트
In Review로 설정해주세요.TIL Blog Post