Loading...

[LeetCode] 33. Search in Rotated Sorted Array (python, 이진탐색) 풀이

가장 작은 원소가 있는 인덱스가 피봇 위치이고 그 위치를 기준으로 값을 찾되, left, right 인덱스는 mid를 기준으로 계산한다 *mid 와 mid_pivot을 따로 계산해준다 class Solution: def search(self, nums: List[int], target: int) -> int: left,right=0,len(nums)-1 while leftnums[right]: left=mid+1 else: right=mid pivot=left left,right=0,len(nums)-1 while left

LeetCode - Array Partition 1

2개씩 짝을 지어 최소값들의 합의 최대값을 구하는 것은 정렬된 배열을 2개씩 묶어서 구하면 된다. 정렬된 수이므로 각 짝의 최대값은 인덱스가 짝수인 수들이며 sorted(nums)[::2]를 통해 짝수번째 수들만 구할 수 있다. class Solution: def arrayPairSum(self, nums: List[int]) -> int: print(sorted(nums)[::2]) return sum(sorted(nums)[::2]) # nums.sort() # result=0 # pair=[] # for i in range(1,len(nums),2): # pair=[nums[i],nums[i-1]] # result+=min(pair) # pair=[] # return result

LeetCode. Group Anagrams (python)

* 알게 된 것 check.values()의 리턴이 배열 형태가 아닌 줄 알고 또 따로 배열을 만들어서 처리해줬었는데 배열로 리턴이 되는 것 같다. sorted는 리스트 형태로 반환한다. sorted(문자열)은 문자열의 각 단어를 정렬한 리스트를 반환해준다. from collections import defaultdict class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: check=defaultdict(list) for item in strs: # print(''.join(sorted(item))) sortedWord=''.join(sorted(item)) check[sortedWord].append(item) ret..

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] 순열 조합 문제인 줄 알았으나 dfs로 풀기 때문에 브루트 포스, 그리디 문제 같다. left는 넣을 수 있는 왼쪽 괄호의 개수, right는 넣을 수 있는 오른쪽 괄호의 개수이다. left,right 하나씩 넣어주지만 오른쪽 괄호는 왼쪽 괄호가 하나이상 존재할 때만 넣을 수 있다. left List[str]: def genParent(s,left,..

680. Valid Palindrome II

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. Note: The string will only contain lowercase characters a-z. The maximum length of the string is 50000. 1. 브루트포스 풀이 (시간 초과) 처음에 이렇게 풀었더니 시간 초과가 나왔다. 배열의 길이가 O(n)인데 ..

[Leetcode] 819. most common word (python, javasciript)

1. python from collections import defaultdict import re class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: dict=defaultdict(int) paragraph=re.sub(r'[^\w]',' ',paragraph) # print(paragraph) for p in paragraph.lower().split(): if p not in banned: dict[p]+=1 return max(dict,key=dict.get) cnt=collections.Counter(dict) 해서 return cnt.most_common(1)[0][0]으로 가져오는 방법도 있다 ..

[LeetCode] 937. Reorder Data in Log Files (python, javascript)

1. python class Solution: def reorderLogFiles(self, logs: List[str]) -> List[str]: nums=[] letters=[] for log in logs: if log.split()[1].isdigit(): nums.append(log) else: letters.append(log) # slice로 잘라서 그 후를 모두 지정할 수 있다 letters.sort(key=lambda x:(x.split()[1:],x.split()[0])) # print(nums) # print(letters) return letters+nums 2. javascript /** * @param {string[]} logs * @return {string[]} */ var..