프라이D
프라이Develog(❁´◡`❁)
프라이D
전체 방문자
오늘
어제
  • ALL (378)
    • TDD, Cleancode with JavaScr.. (5)
    • 프로젝트 (32)
      • work (3)
      • 직접 만드는 기술 블로그 (2)
      • 데일리 옥션 (19)
      • 모락모락 (8)
    • Computer Science (1)
    • Algorithm & 자료구조 (94)
      • 알고리즘 w.JavaScript (53)
      • 자료구조 (5)
      • (인프런) 자바스크립트 알고리즘 문제풀이 (34)
    • JavaScript (45)
      • JavaScript (41)
      • 모던 자바스크립트 Deep Dive (4)
    • WEB (13)
    • 회고 (12)
    • TIL (109)
    • WIL (7)
    • Stacks (20)
      • React.js (6)
      • Next.js (1)
      • Redux (3)
      • Node.js (2)
      • GIT (2)
      • SAP (1)
    • 15일 메이킹 프로젝트 (15)
    • 이전 기록 (14)
    • ETC. (5)
    • ---------------2021 (6)
      • 내일배움단-웹개발 5주 (2)
      • 정보처리기사 (4)

블로그 메뉴

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

공지사항

인기 글

태그

  • 2023 인프콘 후기
  • 내일배움단
  • Til
  • 비트마스크
  • 국비지원
  • nomadcoders
  • 자바스크립트알고리즘
  • 모던자바스크립트딥다이브
  • 코딩프로젝트
  • 투포인터알고리즘
  • 코드스테이츠
  • 자바스크립트
  • vanilaJS
  • 자바스크립트비트마스크
  • 스파르타코딩클럽
  • 내일배움카드
  • 알고리즘
  • nomadcoder
  • JavaScript
  • MySQL

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
프라이D

프라이Develog(❁´◡`❁)

Algorithm & 자료구조/알고리즘 w.JavaScript

[Leetcode] 605. Can Place Flowers

2023. 12. 31. 22:35

 

 

Can Place Flowers - LeetCode

Can you solve this real interview question? Can Place Flowers - You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1'

leetcode.com

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

 

내 풀이

var canPlaceFlowers = function (flowerbed, n) {
  // 흠 뭔가 0의 갯수와 n 을 나누거나 나누어 떨어진 값으로 해결할 수 있을 것 같은데...
  // 일단 유효하게 심을 수 있는 자리의 갯수를 산출해서 이게 n보다 같거나 크면 true 를 리턴할 수 있겠다.
  // 그럼 유효하게 심을 수 있는 자리는 어떻게 구하느냐?
  // 반복문에서 각 자리의 양 옆에 1이 없으면 유효, 아니라면 유효하지 않은 값
  // 그런데 이미 꽃 하나를 심고 나면 다음 자리가 유효하지 않은 자리가 될 수 있으므로...
  // 그냥 자리 남은데에 하나씩 심으면서 n을 감소시키고, n 이 0보다 클 경우 false 를 리턴하는 방법
  // -> 흠 근데 통과를 하지 못하는 20개의 TC 가 존재한다... 어떤 예외가 있을까..?
  // => 첫번째 칸 혹은 마지막 칸도 심을 수 있는데 그 이전, 이후 값을 모두 확인해주고 있어서 그렇다...

  let flowerLeft = n;

  flowerbed.forEach((plot, i) => {
    if (
      plot === 0 &&
      (!flowerbed[i - 1] || flowerbed[i - 1] === 0) &&
      (!flowerbed[i + 1] || flowerbed[i + 1] === 0) &&
      n > 0
    ) {
      flowerbed[i] = 1;
      flowerLeft--;
    }
  });

  return flowerLeft > 0 ? false : true;
};
  •  어휴..~ 지저분해..~

더 나은 풀이

var canPlaceFlowers2 = function (flowerbed, n) {
  let count = 0;
  let pre = -1;
  let next = 1;

  for (let i = 0; i < flowerbed.length; i++, pre++, next++) {
    if (
      getValue(flowerbed, pre) +
        getValue(flowerbed, i) +
        getValue(flowerbed, next) ==
      0
    ) {
      flowerbed[i] = 1;
      count++;
    }
  }

  return count >= n;
};

var getValue = function (flowerbed, i) {
  if (i < 0 || i >= flowerbed.length) {
    return 0;
  }
  return flowerbed[i];
};
  • 조건 대신 변수와 함수를 활용해 조금 더 정리된 풀이
저작자표시 (새창열림)

'Algorithm & 자료구조 > 알고리즘 w.JavaScript' 카테고리의 다른 글

151. Reverse Words in a String  (0) 2024.01.03
[Leetcode] 345. Reverse Vowels of a String  (0) 2024.01.03
[Leetcode] 1431. Kids With the Greatest Number of Candies  (0) 2023.12.31
[Leetcode] 1071. Greatest Common Divisor of Strings  (0) 2023.12.28
[Leetcode] 1768.Merge Strings Alternately  (2) 2023.12.18
    'Algorithm & 자료구조/알고리즘 w.JavaScript' 카테고리의 다른 글
    • 151. Reverse Words in a String
    • [Leetcode] 345. Reverse Vowels of a String
    • [Leetcode] 1431. Kids With the Greatest Number of Candies
    • [Leetcode] 1071. Greatest Common Divisor of Strings
    프라이D
    프라이D
    틀린내용 정정 및 개선사항은 언제든지 댓글 달아주세요 :D

    티스토리툴바