给你一个由互不相同的整数组成的数组 nums。 在一次操作中,你可以交换任意两个相邻元素。 在一...

생성일: 2025년 6월 21일

답변에 사용된 모델 O3 by Chat01

질문

给你一个由互不相同的整数组成的数组 nums。

在一次操作中,你可以交换任意两个相邻元素。

在一个排列中,当所有相邻元素的奇偶性交替出现,我们认为该排列是 有效排列。这意味着每对相邻元素中一个是偶数,一个是奇数。

请返回将 nums 变成任意一种有效排列所需的最小相邻交换次数。

如果无法重排 nums 来获得有效排列,则返回 -1。

示例 1:

输入: nums = [2,4,6,5,7]

输出:3

解释:

将 5 和 6 交换,数组变成 [2,4,5,6,7]

将 5 和 4交换,数组变成 [2,5,4,6,7]

将 6和 7交换,数组变成[2,5,4,7,6]。此时是一个有效排列。因此答案是 3。

示例 2:

输入: nums = [2,4,5,7]

输出: 1

解释:

将 4和 5交换,数组变成 [2,5,4,7]。此时是一个有效排列。因此答案是 1。

示例 3:

输入: nums = [1,2,3]

输出: 0

解释:

数组已经是有效排列,因此不需要任何操作。

示例 4:

输入:nums = [4,5,6,8]

输出:-1

解释:

没有任何一种排列可以满足奇偶交替的要求,因此返回 -1。

提示:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
nums中的所有元素都是 唯一 的

class Solution {
public int minSwaps(int[] nums) {

}
} 解决这个问题,通过所有例子,并且不能超时

사고

Solving minimum swaps for valid arrangement

The user’s asking to solve a problem where an array’s elements need to be reordered into alternating odd-even pairs using the minimum number of adjacent swaps. If it's impossible, we should return -1. The strategy involves checking two possible valid formats: starting with odd or even, then calculating the minimal swaps needed by aligning the sequence with one of those formats. I'll need to implement this efficiently in Java, considering edge cases where rearranging isn't possible.

Finding minimal adjacent swaps

To solve this, I can start by identifying the positions of the odd and even elements in the array. For each valid alternating pattern, I'll compute the total cost of transforming the current positions to the target ones by summing the absolute differences in positions. When doing this, I’ll make sure to check the counts of even and odd elements — if the difference exceeds 1, it's not possible. I can compute the result for both patterns and consider the minimal swaps needed to match the positions.

Calculating minimal adjacent swaps

I’m breaking down how to find the minimal number of adjacent swaps to create an alternating parity pattern. After counting the even and odd positions, I'll calculate moves for both possible patterns (starting with even or odd). The key is to find how much each element needs to shift to its target, summing the absolute differences. I'll ensure the solution handles large inputs efficiently, using long values for large sums due to potential overflow. Time complexity is O(n), which should handle the input limits.

Thought for 27 seconds

답변

思路解析

  1. 合法性判断

    • evenCntoddCnt 为偶数/奇数个数。
    • 交替排列时,两类个数之差不能超过 1;否则必定无法重排,直接返回 -1。
  2. 记录原始下标

    • 扫描一次 nums,把偶数出现的下标存到 evenPos,奇数出现的下标存到 oddPos
    • 两个列表本身保持了元素在原数组中的先后顺序,这一点很关键。
  3. 枚举起始奇偶性

    • 如果 evenCnt == oddCnt,既可以 “偶-奇-偶-奇…” 也可以 “奇-偶-奇-偶…”,两种都要算,取较小者。
    • 如果 evenCnt > oddCnt(只可能多 1 个),排列必须从偶数开头;反之亦然。
  4. 计算最少相邻交换次数

    • 对于某一种起始模式,只需要把数量较多或规定在偶数位(0,2,4…)的那一类按当前顺序放到目标坐标即可。
    • target[i] = 2*i 为第 i 个该类元素理应出现的位置,下标差的绝对值就是它要走的步数;相邻交换一次只能把元素移动 1 位,所以 cost=ipos[i]2icost = \sum_{i} |\,pos[i] - 2i\,|
    • 不必同时对两类元素求和——把偶数放到正确槽位后,奇数自然落到剩余位置,步数不会被遗漏也不会被重复统计。
  5. 复杂度

    • 只需一次遍历 + 最多两次对列表求和,时间 O(n)、空间 O(n)。
    • n ≤ 10^5,步数上界约 1.25×1091.25\times10^9,用 long 保存再强转 int 安全无误。

代码(Java 17)

java
class Solution { public int minSwaps(int[] nums) { int n = nums.length; List<Integer> evenPos = new ArrayList<>(); List<Integer> oddPos = new ArrayList<>(); for (int i = 0; i < n; ++i) { if ((nums[i] & 1) == 0) { evenPos.add(i); } else { oddPos.add(i); } } int evenCnt = evenPos.size(), oddCnt = oddPos.size(); if (Math.abs(evenCnt - oddCnt) > 1) return -1; // 无解 long ans = Long.MAX_VALUE; // 情况 A: 以偶数开头 (偶数占 0,2,4,...) if (evenCnt >= oddCnt) { long cost = 0; for (int i = 0; i < evenPos.size(); ++i) { cost += Math.abs(evenPos.get(i) - (long)(2 * i)); } ans = Math.min(ans, cost); } // 情况 B: 以奇数开头 (奇数占 0,2,4,...) if (oddCnt >= evenCnt) { long cost = 0; for (int i = 0; i < oddPos.size(); ++i) { cost += Math.abs(oddPos.get(i) - (long)(2 * i)); } ans = Math.min(ans, cost); } return (int) ans; // 上限 1.25e9,fits in int } }

例子核对

输入计算过程输出
[2,4,6,5,7]仅可偶数开头: $0-0
[2,4,5,7]偶数开头得 1,奇数开头得 3 ⇒ 取 11
[1,2,3]只能奇数开头,代价 00
[4,5,6,8]|even-odd| = 2 > 1 ⇒ -1-1

全部符合题意且 O(n) 通过大数据不会超时。

이 Q&A 공유하기