通过根据给定规则乘以边界元素来查找最后剩余的 Array 元素
给定一个数组arr[] ,任务是在应用以下操作后找到数组中唯一剩余的元素,直到数组中只剩下一个元素。在一次操作中,将该数组的边界元素相乘,如果数组的大小为:
- 偶数:在数组中间插入积,去掉边界元素
- 奇数:乘积减去中间元素,用绝对差代替中间元素,去掉边界元素。
例子:
Input: arr[] = [ 1, 2, 3, 4, 5, 6 ]
Output: 8
Explanation: See the image below for explanation.
Input: arr[] = [ 3, 5, 1, 8, 9]
Output: 14
方法:解决方案基于贪婪方法。从数组的末端删除元素并将数据插入到数组的中间。现在按照以下步骤解决此问题:
- 运行 while 循环,直到数组arr[]的大小大于 1。在此循环的每次迭代中:
- 取第一个和最后一个元素的乘积,然后弹出它们。
- 如果数组的大小是偶数,则将乘积插入数组arr[]的中间。
- 如果它是奇数,则从产品中减去中间元素并用中间元素替换它。
- 循环结束后,打印数组中唯一剩余的元素。
Java
// Java program for the baove approach
import java.util.ArrayList;
import java.util.Arrays;
class GFG
{
// Function to reduce array
static void PSarray(ArrayList A)
{
while (A.size() != 1)
{
// If size of array is Even
if (A.size() % 2 == 0){
// Product of boundary element
int x = A.get(0)*A.get(A.size()-1);
A.remove(0);
A.remove(A.size() - 1);
int n = A.size();
// Insert product in middle of element
A.add(n/2, x);
}
// Else if size of array is Odd
else {
int x = A.get(0)*A.get(A.size() - 1);
A.remove(0);
A.remove(A.size() - 1);
int n = A.size();
// Subtract middle element from product and
// replace middle element
A.set(n / 2, x - A.get(n / 2));
}
}
// Print the last remaining array element
System.out.println(A);
}
// Driver Code
public static void main(String[] args) {
Integer []arr = {1, 2, 3, 4, 5, 6};
ArrayList A = new ArrayList<>(Arrays.asList(arr));
PSarray(A);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python program for the baove approach
# Function to reduce array
def PSarray(A):
while len(A) != 1:
# If size of array is Even
if len(A) % 2 == 0:
# Product of boundary element
x = A.pop(0)*A.pop()
n = len(A)
# Insert product in middle of element
A.insert(n//2, x)
# Else if size of array is Odd
else:
x = A.pop(0)*A.pop()
n = len(A)
# Subtract middle element from product and
# replace middle element
A[n//2] = x-A[n//2]
# Print the last remaining array element
print(A[0])
# Driver Code
if __name__ == "__main__":
A = [1, 2, 3, 4, 5, 6]
PSarray(A)
C#
// C# program for the baove approach
using System;
using System.Collections.Generic;
public class GFG
{
// Function to reduce array
static void PSarray(List A)
{
while (A.Count != 1)
{
// If size of array is Even
if (A.Count % 2 == 0){
// Product of boundary element
int x = A[0]*A[A.Count-1];
A.RemoveAt(0);
A.RemoveAt(A.Count - 1);
int n = A.Count;
// Insert product in middle of element
A.Insert(n/2,x);
}
// Else if size of array is Odd
else {
int x = A[0]*A[A.Count - 1];
A.RemoveAt(0);
A.RemoveAt(A.Count - 1);
int n = A.Count;
// Subtract middle element from product and
// replace middle element
A[n / 2] = x - A[n / 2];
}
}
// Print the last remaining array element
A.ForEach(x=>Console.Write(x));
}
// Driver Code
public static void Main(String[] args) {
int []arr = {1, 2, 3, 4, 5, 6};
List A = new List(arr);
PSarray(A);
}
}
// This code is contributed by 29AjayKumar
Javascript
输出
8
时间复杂度: O(N 2 )
辅助空间: O(1)