[LeetCode] 2422. Merge Operations to Turn Array Into a Palindrome
You are given an array nums
consisting of positive integers.
You can perform the following operation on the array any number of times:
- Choose any two adjacent elements and replace them with their sum.
- For example, if
nums = [1,2,3,1]
, you can apply one operation to make it[1,5,1]
.
- For example, if
Return the minimum number of operations needed to turn the array into a palindrome.
Example 1:
Input: nums = [4,3,2,1,2,3,1] Output: 2 Explanation: We can turn the array into a palindrome in 2 operations as follows: - Apply the operation on the fourth and fifth element of the array, nums becomes equal to [4,3,2,3,3,1]. - Apply the operation on the fifth and sixth element of the array, nums becomes equal to [4,3,2,3,4]. The array [4,3,2,3,4] is a palindrome. It can be shown that 2 is the minimum number of operations needed.
Example 2:
Input: nums = [1,2,3,4] Output: 3 Explanation: We do the operation 3 times in any position, we obtain the array [10] at the end which is a palindrome.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
使用合并操作将数组转换为回文序列。
给定一个由 正整数 组成的数组 nums。
可以对阵列执行如下操作,次数不限:
选择任意两个 相邻 的元素并用它们的 和 替换 它们。
例如,如果 nums = [1,2,3,1],则可以应用一个操作使其变为 [1,5,1]。
返回将数组转换为 回文序列 所需的 最小 操作数。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-operations-to-turn-array-into-a-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是贪心 + 双指针。从数组的左右两边开始看,
- 如果 nums[left] == nums[right],两边数字一样,left++, right--,继续比较中间的元素
- 如果 nums[left] != nums[right],两边数字不一样,此时需要合并,谁较小就让谁与其邻居元素合并,并移动指针
- 当 left 指针与 right 指针相遇的时候,返回一共合并了几次
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int minimumOperations(int[] nums) { 3 int res = 0; 4 int left = 0; 5 int right = nums.length - 1; 6 while (left < right) { 7 if (nums[left] < nums[right]) { 8 nums[left + 1] += nums[left]; 9 left++; 10 res++; 11 } else if (nums[left] > nums[right]) { 12 nums[right - 1] += nums[right]; 13 right--; 14 res++; 15 } else { 16 left++; 17 right--; 18 } 19 } 20 return res; 21 } 22 }