LeetCode 2808. Minimum Seconds to Equalize a Circular Array
You are given a?0-indexed?array?nums
?containing?n
?integers.
At each second, you perform the following operation on the array:
For every index?
i
?in the range?[0, n - 1]
, replace?nums[i]
?with either?nums[i]
,?nums[(i - 1 + n) % n]
, or?nums[(i + 1) % n]
.
Note?that all the elements get replaced simultaneously.
Return?the?minimum?number of seconds needed to make all elements in the array?nums
?equal.
?
Example 1:
Input: nums = [1,2,1,2]
Output: 1
Explanation:?
We can equalize the array in 1 second in the following way: - At 1st second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2]. It can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.
Example 2:
Input: nums = [2,1,3,3,2]
Output: 2
Explanation:
We can equalize the array in 2 seconds in the following way: - At 1st second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3]. - At 2nd second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3]. It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.
Example 3:
Input: nums = [5,5,5,5]
Output: 0
Explanation:?
We don't need to perform any operations as all elements in the initial array are the same.
?
Constraints:
1 <= n == nums.length <= 105
1 <= nums[i] <= 109
------------------------------------------
給你一個下標從?0?開始長度為?n
?的數(shù)組?nums
?。
每一秒,你可以對數(shù)組執(zhí)行以下操作:
對于范圍在?
[0, n - 1]
?內(nèi)的每一個下標?i
?,將?nums[i]
?替換成?nums[i]
?,nums[(i - 1 + n) % n]
?或者?nums[(i + 1) % n]
?三者之一。
注意,所有元素會被同時替換。
請你返回將數(shù)組?nums
?中所有元素變成相等元素所需要的?最少?秒數(shù)。
?
示例 1:
輸入:nums = [1,2,1,2]
輸出:1
解釋:我們可以在 1 秒內(nèi)將數(shù)組變成相等元素: - 第 1 秒,將每個位置的元素分別變?yōu)?[nums[3],nums[1],nums[3],nums[3]] 。變化后,nums = [2,2,2,2] 。 1 秒是將數(shù)組變成相等元素所需要的最少秒數(shù)。
示例 2:
輸入:nums = [2,1,3,3,2]
輸出:2
解釋:我們可以在 2 秒內(nèi)將數(shù)組變成相等元素: - 第 1 秒,將每個位置的元素分別變?yōu)?[nums[0],nums[2],nums[2],nums[2],nums[3]] 。變化后,nums = [2,3,3,3,3] 。 - 第 2 秒,將每個位置的元素分別變?yōu)?[nums[1],nums[1],nums[2],nums[3],nums[4]] 。變化后,nums = [3,3,3,3,3] 。 2 秒是將數(shù)組變成相等元素所需要的最少秒數(shù)。
示例 3:
輸入:nums = [5,5,5,5]
輸出:0
解釋:不需要執(zhí)行任何操作,因為一開始數(shù)組中的元素已經(jīng)全部相等。
?
Runtime:?77 ms, faster than?49.12%?of?Java?online submissions for?Minimum Seconds to Equalize a Circular Array.
Memory Usage:?90.3 MB, less than?6.80%?of?Java?online submissions for?Minimum Seconds to Equalize a Circular Array.
------------------------------
如果數(shù)組中沒有相同的數(shù)字,那么肯定話費的時間是最長的也就是n/2了,既然可以改變左右2個相鄰的數(shù)字,那么我們將相同元素的索引值放到一個鏈表里面,注意最后加一個n,這樣就是環(huán)形鏈表了,
然后依次去判斷2個index的最值即可,
最后跟n/2取最小值即可;
下面是代碼: