From 9ef001ea6ff3b4624fc1bfd686c63993dcd69d07 Mon Sep 17 00:00:00 2001 From: gameloader Date: Wed, 6 Nov 2024 13:48:29 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index d468150..67feffc 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -17092,3 +17092,62 @@ public: } }; ``` +## day243 2024-11-06 +### 3011. Find if Array Can Be Sorted +You are given a 0-indexed array of positive integers nums. + +In one operation, you can swap any two adjacent elements if they have the same number of +set bits +. You are allowed to do this operation any number of times (including zero). + +Return true if you can sort the array, else return false. + +![1106sIaxQDdMbk32](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/1106sIaxQDdMbk32.png) + +### 题解 +本题要求从小到大排列数组,对于包含个数相同的1的连续数字,这些数字之间总可以通过不断的相邻交换最终从小到大排列。因此我们不必关心这些数字具体的排序方式,只需记录连续数字中值最大的那个,当遇到新的一组包含不同个数1的数字时只需该组数字中最小值大于前面组数字的最大值数组整体即可完成排序,若小于最大值则由于该数字包含的1的个数和前面的数字不同,该数字不可能与前面的数字交换位置,因此该数字不可能交换到数组的前面,此时就无法成功排序。 + +统计某个数字n中包含的二进制1的个数,可以使用n&(n-1),n&(n-1)每次可以消掉一个尾部所有0之前的第一个二进制1,通过不断的进行n&(n-1)的变换,记录变换的次数,当n为0时变换的次数即为该数字中包含的1的个数。 + +### 代码 +```cpp +class Solution { +public: + bool canSortArray(vector& nums) { + int currentbit = count(nums[0]); + int lastmax = 0; + int max = 0; + int min = 0; + int bit = 0; + for (int num : nums){ + bit = count(num); + if (currentbit == bit){ + if (num < lastmax){ + return false; + } + if (num > max){ + max = num; + } + }else{ + if (num < max){ + return false; + }else{ + lastmax = max; + currentbit = bit; + max = num; + } + } + } + return true; + } + + int count(int num){ + int result = 0; + while(num != 0){ + num = num&(num-1); + result++; + } + return result; + } +}; +```