[Mock] Apple 1

shsh·2021년 3월 30일
0

Mock

목록 보기
18/93

268. Missing Number

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

My Answer 1: Accepted (Runtime: 128 ms - 73.40% / Memory Usage: 15.3 MB - 95.41%)

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        nums.sort()
        
        # 0 ~ n 까지 숫자가 연속적 => 마지막 값 + 1 return
        if nums[-1] == len(nums)-1:
            return nums[-1] + 1
        
        # 중간에 빈 곳이 있으면 0 부터 빈 곳 찾아서 return
        start = 0
        for n in nums:
            if n != start:
                return start
            start += 1
            
        return start

sort 로 정렬한 후

nums 가 연속적인 숫자면 예외처리 미리 해주고

중간에 빈 곳이 있으면 0 부터 빈 곳을 찾아서 return 하도록 함


38. Count and Say

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

For example, the saying and conversion for digit string "3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.

My Answer 1: Accepted (Runtime: 40 ms - 88.12% / Memory Usage: 14.3 MB - 54.46%)

class Solution:
    def countAndSay(self, n: int) -> str:
        # 이거.. 예시 사진을 보니까.. 그지 같았던게 생각나요
        
        # 초기값 => "1"
        say = "1"
        for i in range(1, n):
            tmp = ""
            cnt = 0
            now = say[0]
            # say 의 각 숫자(now)마다 개수(cnt) 세기
            for j in range(len(say)):
                if say[j] != now:   # 보던 숫자(now)와 다른 숫자를 만날 때마다 tmp 에 저장
                    tmp += str(cnt) + now
                    now = say[j]
                    cnt = 0
                cnt += 1
            tmp += str(cnt) + now
            say = tmp
        
        return say

say 의 초기값을 1 로 설정하고 n 만큼 반복문을 돌려서 say 의 각 숫자마다 몇번 나오는지 세어줌

보고 있던 숫자와 다른 숫자가 나오면 tmp 에 [개수+숫자] 형태로 넣어주기

애플이 문제들이 익숙하네요~~

이분 전부터 싫어요 눌러두셨네요^^

profile
Hello, World!

0개의 댓글

Powered by GraphCDN, the GraphQL CDN