Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

1437. Check If All 1's Are at Least Length K Places Away (1 항목 모두 길이 K 이상 떨어져 있는지 확인) 본문

코딩 테스트/LeetCode

1437. Check If All 1's Are at Least Length K Places Away (1 항목 모두 길이 K 이상 떨어져 있는지 확인)

포카리tea 2023. 5. 31. 01:17

이진 배열 숫자와 정수 k를 지정하면 모든 1이 서로 k자리 이상 떨어져 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

 

예시 1:

입력: nums = [1,0,0,0,1,0,0,1], k = 2
출력: true
설명: 각각의 1은 서로 최소 2곳 이상 떨어져 있습니다.

 

예시 2:

입력: nums = [1,0,0,1,0,1], k = 2
출력: false
설명: 두 번째 1과 세 번째 1은 서로 하나밖에 떨어져 있지 않습니다.

 

조건:

  • 1 <= nums.length <= 105
  • 0 <= k <= nums.length
  • nums[i] is 0 or 1

 

정답:

public class Solution {
    public bool KLengthApart(int[] nums, int k) {
        bool ischeck = true;
        int? location = null;
        
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] == 1)
            {
                if (location == null)
                {
                    location = i;
                }
                else
                {
                    if (i - location <= k)
                    {
                        ischeck = false;
                    }

                    location = i;
                }
            }
        }
        
        return ischeck;
    }
}

해설: 

1 위치를 기억하고 그 이후의 1 위치를 빼고 그 수가 k보다 같거나 낮으면 ischeck를 false로 바꿔주어 return해주었습니다.