You are given a 0-indexed array nums consisting of n positive integers.
The array nums is called alternating if:
nums[i - 2] == nums[i], where 2 <= i <= n - 1.
nums[i - 1] != nums[i], where 1 <= i <= n - 1.
In one operation, you can choose an index i and change nums[i] into any positive integer.
Return the minimum number of operations required to make the array alternating.
Example 1:
Input: nums = [3,1,3,2,4,3]
Output: 3
Explanation:
One way to make the array alternating is by converting it to [3,1,3,1,3,1].
The number of operations required in this case is 3.
It can be proven that it is not possible to make the array alternating in less than 3 operations.
Example 2:
Input: nums = [1,2,2,2,2]
Output: 2
Explanation:
One way to make the array alternating is by converting it to [1,2,1,2,1].
The number of operations required in this case is 2.
Note that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.
Constraints:
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 105
alternating 换句话说就是奇数位相等且偶数位相等且奇偶位不相等。
我们分别找出奇数位与偶数位数字的出现频次,假设我们奇数位 1 的出现频次最高,偶数位 2 的出现频次最高,我们只要让奇数位其他不是 1 的数字变成 1 和偶数位不是 2 的数字变成 2 即可得到 alternating 数组, 并且整个变换过程的步骤也是最少的。但是奇数位频次最高和偶数位频次最高的数字可能是同一个数字, 这就违反了奇偶位不相等的要求, 这种情况下我们要么放弃奇数位去找下一个频次最高的奇数位, 要么放弃偶数位找下一个频次最高的偶数位, 我们从中找最少步骤即可。 但是我们要注意奇数位只有一个数字或者偶数位只有一个数字的情况, 这种情况下,如果奇数位只有一个数字,那我们只能去找下一个频次最高的偶数位, 如果偶数位为一个数字,那我们只能去找下一个频次最高的奇数位。如果两者都是只有一个数字, 那证明整个数组只有一个数字, 那我们只需要看是奇数位多还是偶数位多, 用总数减去多的那个即可
use std::collections::{BinaryHeap, HashMap};
impl Solution {
pub fn minimum_operations(nums: Vec<i32>) -> i32 {
let total = nums.len() as i32;
match total {
0 | 1 => 0,
2 => {
if nums[0] == nums[1] {
1
} else {
0
}
}
_ => {
let mut even_frequences = HashMap::new();
let mut odd_frequences = HashMap::new();
for (i, n) in nums.into_iter().enumerate() {
if i % 2 == 0 {
*even_frequences.entry(n).or_insert(0) += 1;
continue;
}
*odd_frequences.entry(n).or_insert(0) += 1;
}
let mut even_frequences: BinaryHeap<(i32, i32)> =
even_frequences.into_iter().map(|(k, v)| (v, k)).collect();
let mut odd_frequences: BinaryHeap<(i32, i32)> =
odd_frequences.into_iter().map(|(k, v)| (v, k)).collect();
let (even_count, even_num) = even_frequences.pop().unwrap();
let (odd_count, odd_num) = odd_frequences.pop().unwrap();
if even_num != odd_num {
return total - even_count - odd_count;
}
if let Some((next_even_count, _)) = even_frequences.pop() {
if let Some((next_odd_count, _)) = odd_frequences.pop() {
return (total - odd_count - next_even_count)
.min(total - even_count - next_odd_count);
}
return total - odd_count - next_even_count;
}
if let Some((next_odd_count, _)) = odd_frequences.pop() {
return total - even_count - next_odd_count;
}
(total - even_count).min(total - odd_count)
}
}
}
}