본문 바로가기

카테고리 없음

1.15 코테 일지

1. 배열 복사

https://leetcode.com/problems/concatenation-of-array/

concatenation of array 

 

Concatenation of Array - LeetCode

Can you solve this real interview question? Concatenation of Array - Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is th

leetcode.com

나는 밑에와 같은 코드를 짯다.

        ans= []
        ans[:] = nums
        ans[len(nums):] = nums
        return ans

 

근데 그냥 return nums *2를 해주었으면 됐다.

 

2. 배열 또는 stack의 가장 마지막 원소

https://leetcode.com/problems/baseball-game/submissions/1146782520/

baseball game

 

Baseball Game - LeetCode

Can you solve this real interview question? Baseball Game - You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings operations, where operations[i] is

leetcode.com

stack[-1]을 해주면 된다.

이 때, stack이 empty list의 경우 

try문을 써주거나 

간단히 if stack

 

3. list의 합 

https://leetcode.com/problems/baseball-game/submissions/1146782520/

baseball game

 

for문 돌리지 말고 sum(list)

 

4. 효율적인 짝 관리

https://leetcode.com/problems/valid-parentheses/submissions/1146790814/

valid parentheses

 

Valid Parentheses - LeetCode

Can you solve this real interview question? Valid Parentheses - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the sam

leetcode.com

class Solution(object):
    def isValid(self, s):
        stack = []
        open = ['(','{','[']
        close = [')','}',']']
        for string in s :
            if string in open :
                stack.append(string)
            else :
                index = close.index(string)
                if len(stack) == 0 :
                    return False
                elif stack[-1] == open[index] :
                    stack.pop()
                else :
                    return False
        if len(stack) == 0 :
            return True
        else :
            return False
 
       

처럼 배열로 따로 하지말고 다음과 같이 dictionary로 관리한다. 

class Solution(object):
    def isValid(self, s):
        stack=[]
        mapp={'(':')','{':'}','[':']'}
        for x in s:
            if x in mapp.keys():
                stack.append(x)
            elif x in mapp.values():
                if not stack or mapp[stack.pop()]!=x:
                    return False
        return not stack

 

5. 기타

a) 단순반복

print("hello world")를 다섯번 출력하고 싶으면

for _ in range(5) 사용