saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 개발자 취업준비
  • 딕셔너리
  • 파이썬
  • LeetCode
  • 개발자
  • 취준
  • two pointer
  • 딥러닝
  • 취업준비
  • 릿코드
  • 리트코드
  • 알고리즘문제해결
  • 알고리즘
  • 문제해결능력
  • 백준
  • c++
  • Python
  • 온라인저지
  • DFS
  • BFS

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeetCode] 251. Flatten 2D Vector

2022. 7. 29. 18:33

251. Flatten 2D Vector

Medium
602338Add to ListShare

Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

Implement the Vector2D class:

  • Vector2D(int[][] vec) initializes the object with the 2D vector vec.
  • next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.
  • hasNext() returns true if there are still some elements in the vector, and false otherwise.

 

Example 1:

Input
["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"]
[[[[1, 2], [3], [4]]], [], [], [], [], [], [], []]
Output
[null, 1, 2, 3, true, true, 4, false]

Explanation
Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);
vector2D.next();    // return 1
vector2D.next();    // return 2
vector2D.next();    // return 3
vector2D.hasNext(); // return True
vector2D.hasNext(); // return True
vector2D.next();    // return 4
vector2D.hasNext(); // return False

 

Constraints:

  • 0 <= vec.length <= 200
  • 0 <= vec[i].length <= 500
  • -500 <= vec[i][j] <= 500
  • At most 105 calls will be made to next and hasNext.

 

Follow up: As an added challenge, try to code it using only iterators in C++ or iterators in Java.

 


문제 풀이

문제 접근

  1. 문제 제한이 타이트하지 않다, 구현 문제 인듯하다.
  2. 파이썬의 Flatten 함수를 구현해야한다.
  3. Follow up 에 이터레이터를 사용하라고 되어있는데 파이썬이라 패스.

풀이

  1. 클래스 초기화 부분에서 1차원 리스트 생성한다.
  2. 문제 제한에서 2차원 리스트 안에 1차원 리스트 크기가 0일 수도 있기 때문에 예외 처리한다.
  3. 2중 for 문으로 하나씩 넣어준다. [고차원 배열의 경우 재귀사용 필수]
  4. next 함수는 hasNext 함수를 사용하여 존재할 경우 답을 임시 저장 후, 인덱스 증가, 그리고 답을 반환한다.
  5. hasNext 함수는 초기화에서 만들었던 인덱스(이터레이터 대체)가 리스트 길이를 넘으면 False 리턴, 나머지는 True 반환한다.

소스코드

class Vector2D:

    def __init__(self, vec: List[List[int]]):
        self.flatten2D = []
        self.index = 0
        for l in vec:
            if len(l) == 0: continue
            for num in l:
                self.flatten2D.append(num)

    def next(self) -> int:
        if self.hasNext:
            ans = self.flatten2D[self.index]
            self.index += 1
            return ans

    def hasNext(self) -> bool:
        if self.index < len(self.flatten2D):
            return True
        return False


# Your Vector2D object will be instantiated and called as such:
# obj = Vector2D(vec)
# param_1 = obj.next()
# param_2 = obj.hasNext()

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 621. Task Scheduler  (0) 2022.07.30
[LeetCode] 916. Word Subsets  (0) 2022.07.30
[LeetCode] 890. Find and Replace Pattern  (0) 2022.07.29
물건 사고 파는 문제 파이썬 order, sell, return  (0) 2022.03.07
a+b=c 숫자식에서 각 숫자의 한자리 수 치환을 통해 식을 맞게 만드는 방법  (0) 2022.03.07
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 621. Task Scheduler
    • [LeetCode] 916. Word Subsets
    • [LeetCode] 890. Find and Replace Pattern
    • 물건 사고 파는 문제 파이썬 order, sell, return
    saurus2
    saurus2
    Simple is Best

    티스토리툴바