본문 바로가기

array7

Leetcode 136. Single Number 1 2 3 4 pythonclass Solution: def singleNumber(self, nums: List[int]) -> int: for i in nums: if nums.count(i)==1: return i cs 2021. 9. 24.
Leetcode 1979. Find Greatest Common Divisor of Array 1 2 3 4 5 6 7 8 class Solution: def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) def findGCD(self, nums: List[int]) -> int: return ( gcd(max(nums),min(nums))) cs gcd구하는 함수는 재귀로 짜고 nums에서 가장 큰 값, 가장 작은 값의 gcd를 return 하면됩니다 주의할점은 a가 b보다 크거나 같아야됩니다 2021. 8. 31.
Leetcode 1588. Sum of All Odd Length Subarrays 1 2 3 4 5 6 7 class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: ans=0 for i in range(len(arr)): for j in range(i, len(arr),2): ans+=sum(arr[i:j+1]) return ans Colored by Color Scripter cs 2021. 8. 31.
Leetcode 1720. Decode XORed Array 1 2 3 4 5 6 class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: ans=[first] for i in encoded: ans.append(i^ans[-1]) return ans Colored by Color Scripter cs XOR -> Exclusive OR 문제구요 학부때 배웠던 Logical circuit 생각해보시면 쉽게 풀수있는데 파이썬에서는 " ^ " operator가 XOR 입니다. 아마 다른언어에서는 power의 개념으로 쓰이는 operator죠 2021. 8. 31.
Leetcode 682. Baseball Game 1 2 3 4 5 6 7 8 9 class Solution: def calPoints(self, ops: List[str]) -> int: tmp=[] for i in ops: if i=='C': tmp.pop() elif i=='D':tmp.append (tmp[-1]*2) elif i=="+":tmp.append(tmp[-1]+tmp[-2]) else : tmp.append(int(i)) return (sum(tmp)) cs 2021. 8. 30.
Leetcode 1441 Build an Array with Stack Operations 1 2 3 4 5 6 7 8 9 10 11 class Solution: def buildArray(self, target: List[int], n: int) -> List[str]: myn=max(target) tmp= [i+1 for i in range(myn)] ans=[] for i in tmp: if i in target: ans.append("Push") else: ans.append("Push") ans.append("Pop") return ans Colored by Color Scripter cs n으로 만들어진 List를 바탕으로 target을 만들어야하는데 문제에서 언급한 Push, Pop 으로 만들면되는데 주의할것이 target의 가장 큰 값을 for문의 range에 넣으면됩니다 2021. 8. 30.
Leetcode 1877. Minimize Maximum Pair Sum in Array 1 2 3 4 5 6 7 class Solution: def minPairSum(self, nums: List[int]) -> int: nums.sort() tmp=[] for i in range(len(nums)//2): tmp.append(nums[i]+nums[-(i+1)]) return max(tmp) cs 문제 전제 조건 처럼 쌍을 만들려면 nums 리스트를 오름차순으로 정렬해주고 양끝을 쌍으로 묶어줘야합니다. 그 쌍의 합을 tmp 리스트에 넣어주고 그 중에서 최댓값을 리턴하면됩니다 2021. 8. 26.