3011. Find if Array Can Be Sorted
Difficulty: Medium
Topics: Array, Bit Manipulation, Sorting
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 bits1. You are allowed to do this operation any number of times (including zero).
Return true if you can sort the array, else return false.
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
Solution:
We need to determine if the array can be sorted by only swapping adjacent elements that have the same number of set bits in their binary representation. Here’s the plan:
Key Observation: The operation allows us to swap adjacent elements only if they have the same number of set bits. This restricts swapping across elements with different numbers of set bits.
Plan:
Steps:
Let's implement this solution in PHP: 3011. Find if Array Can Be Sorted
Explanation:
- countSetBits Function: Counts the number of set bits in a number using bitwise operations.
- Grouping Elements: bitGroups is an associative array where each key represents the set bit count, and each value is an array of numbers with that many set bits.
Sorting and Rebuilding:
- We iterate over nums to group elements by their set bit count.
- We sort each group independently.
- We then reconstruct the array by inserting each sorted group element in its original order.
- Finally, we check if the reconstructed array is sorted in non-decreasing order. If it is, return true; otherwise, return false.
Final Comparison: Compare the rebuilt array with a fully sorted version of nums. If they match, return true; otherwise, return false.
Complexity Analysis
This solution ensures that we only swap adjacent elements with the same set bit count, achieving a sorted order if possible.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Set Bit A set bit refers to a bit in the binary representation of a number that has a value of 1. ↩
The above is the detailed content of Find if Array Can Be Sorted. For more information, please follow other related articles on the PHP Chinese website!