| | 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.FindIfArrayCanBeSorted; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindIfArrayCanBeSortedTwoPass : IFindIfArrayCanBeSorted |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log k) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public bool CanSortArray(int[] nums) |
| 3 | 24 | | { |
| 30 | 25 | | for (var i = 0; i < nums.Length - 1; i++) |
| 12 | 26 | | { |
| 12 | 27 | | if (nums[i] <= nums[i + 1]) |
| 6 | 28 | | { |
| 6 | 29 | | continue; |
| | 30 | | } |
| | 31 | |
|
| 6 | 32 | | if (GetSetBitsCount(nums[i]) == GetSetBitsCount(nums[i + 1])) |
| 6 | 33 | | { |
| 6 | 34 | | (nums[i], nums[i + 1]) = (nums[i + 1], nums[i]); |
| 6 | 35 | | } |
| | 36 | | else |
| 0 | 37 | | { |
| 0 | 38 | | return false; |
| | 39 | | } |
| 6 | 40 | | } |
| | 41 | |
|
| 28 | 42 | | for (var i = nums.Length - 1; i >= 1; i--) |
| 12 | 43 | | { |
| 12 | 44 | | if (nums[i] >= nums[i - 1]) |
| 8 | 45 | | { |
| 8 | 46 | | continue; |
| | 47 | | } |
| | 48 | |
|
| 4 | 49 | | if (GetSetBitsCount(nums[i]) == GetSetBitsCount(nums[i - 1])) |
| 3 | 50 | | { |
| 3 | 51 | | (nums[i], nums[i - 1]) = (nums[i - 1], nums[i]); |
| 3 | 52 | | } |
| | 53 | | else |
| 1 | 54 | | { |
| 1 | 55 | | return false; |
| | 56 | | } |
| 3 | 57 | | } |
| | 58 | |
|
| 2 | 59 | | return true; |
| 3 | 60 | | } |
| | 61 | |
|
| | 62 | | private static int GetSetBitsCount(int number) |
| 20 | 63 | | { |
| 20 | 64 | | var count = 0; |
| | 65 | |
|
| 86 | 66 | | while (number > 0) |
| 66 | 67 | | { |
| 66 | 68 | | count += number & 1; |
| | 69 | |
|
| 66 | 70 | | number >>= 1; |
| 66 | 71 | | } |
| | 72 | |
|
| 20 | 73 | | return count; |
| 20 | 74 | | } |
| | 75 | | } |