| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.CheckIfGridCanBeCutIntoSections; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CheckIfGridCanBeCutIntoSectionsSorting : ICheckIfGridCanBeCutIntoSections |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(log n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <param name="rectangles"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public bool CheckValidCuts(int n, int[][] rectangles) |
| 3 | 25 | | { |
| 3 | 26 | | return CheckCuts(rectangles, 0) || CheckCuts(rectangles, 1); |
| 3 | 27 | | } |
| | 28 | |
|
| | 29 | | private static bool CheckCuts(int[][] rectangles, int dimension) |
| 5 | 30 | | { |
| 29 | 31 | | Array.Sort(rectangles, (a, b) => a[dimension].CompareTo(b[dimension])); |
| | 32 | |
|
| 5 | 33 | | var gapCount = 0; |
| 5 | 34 | | var furthestEnd = rectangles[0][dimension + 2]; |
| | 35 | |
|
| 40 | 36 | | for (var i = 1; i < rectangles.Length; i++) |
| 17 | 37 | | { |
| 17 | 38 | | var start = rectangles[i][dimension]; |
| 17 | 39 | | var end = rectangles[i][dimension + 2]; |
| | 40 | |
|
| 17 | 41 | | if (furthestEnd <= start) |
| 6 | 42 | | { |
| 6 | 43 | | gapCount++; |
| | 44 | |
|
| 6 | 45 | | if (gapCount >= 2) |
| 2 | 46 | | { |
| 2 | 47 | | return true; |
| | 48 | | } |
| 4 | 49 | | } |
| | 50 | |
|
| 15 | 51 | | furthestEnd = Math.Max(furthestEnd, end); |
| 15 | 52 | | } |
| | 53 | |
|
| 3 | 54 | | return false; |
| 5 | 55 | | } |
| | 56 | | } |