Class Solution
-
- All Implemented Interfaces:
public final class Solution3644 - Maximum K to Sort a Permutation.
Medium
You are given an integer array
numsof lengthn, wherenumsis a permutation of the numbers in the range[0..n - 1].You may swap elements at indices
iandjonly ifnums[i] AND nums[j] == k, whereANDdenotes the bitwise AND operation andkis a non-negative integer.Return the maximum value of
ksuch that the array can be sorted in non-decreasing order using any number of such swaps. Ifnumsis already sorted, return 0.A permutation is a rearrangement of all the elements of an array.
Example 1:
Input: nums = 0,3,2,1
Output: 1
Explanation:
Choose
k = 1. Swappingnums[1] = 3andnums[3] = 1is allowed sincenums[1] AND nums[3] == 1, resulting in a sorted permutation:[0, 1, 2, 3].Example 2:
Input: nums = 0,1,3,2
Output: 2
Explanation:
Choose
k = 2. Swappingnums[2] = 3andnums[3] = 2is allowed sincenums[2] AND nums[3] == 2, resulting in a sorted permutation:[0, 1, 2, 3].Example 3:
Input: nums = 3,2,1,0
Output: 0
Explanation:
Only
k = 0allows sorting since no greaterkallows the required swaps wherenums[i] AND nums[j] == k.Constraints:
<code>1 <= n == nums.length <= 10<sup>5</sup></code>
0 <= nums[i] <= n - 1numsis a permutation of integers from0ton - 1.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntegersortPermutation(IntArray nums)-
-
Method Detail
-
sortPermutation
final Integer sortPermutation(IntArray nums)
-
-
-
-