假设我有一个数组 A。仅当第 i 个元素同时具有相邻元素(即第 (i-1) 个和第 (i+1) 个)时,我才需要删除所有第 i 个元素,并且还缩小了当找到该元素时的数组。另外,如果任何此类元素满足此条件,则每次也会根据以下公式计算其成本:
成本 = (A[i]*A[i-1]) + (A[i]*A[i+1]) + (A[i-1]*A[i+1]) ; 示例:
A = {1,2,3,4}
删除元素“2”后: A = {1,3,4}
删除元素“3”后: A = {1,4}
我不知道如何使用ArrayList。有人可以指导我仅使用数组概念来完成此任务吗,因为我无法继续解决这个问题?
PS:不是作业
这是我的代码:
import java.util.*;
class TestClass
{
public static void main(String args[] ) throws Exception
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int cost=0;
for (int i = 0; i < T; i++) // scanning no. of test cases
{
int N = sc.nextInt(); // scanning no. of elements
int[] A = new int[N];
for(int j=0 ; j<N ; j++)
{
A[j] = sc.nextInt();
}
while (A.length>2)
{
cost = cost + getResultForLocation(A, 1);
A = reduceArray(A, 1);
}
}
System.out.println(cost);
}
static int getResultForLocation(int[] array, int location)
{
int sum = 0;
sum = sum + (array[location] * array[location - 1]) + (array[location] * array[location + 1]) + (array[location - 1] * array[location + 1]);
return sum;
}
static int[] reduceArray (int[] array, int locationToRemove)
{
if (array==null || array.length<=2)
{
return array;
}
if (locationToRemove == array.length || locationToRemove==1)
{
return array;
}
int[] returnArray = new int[array.length-1];
for (int i=0;i<locationToRemove;i++)
{
returnArray[i]=array[i];
}
for (int i=locationToRemove;i<array.length-1;i++)
{
returnArray[i]=array[i+1];
}
return returnArray;
}
}
最佳答案
看看这些方法(使用您的代码):
import java.util.*;
class TestClass
{
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
int numberOfTests = sc.nextInt();
int cost = 0;
for (int i = 0; i < numberOfTests; i++) // scanning no. of test cases
{
int arraySize = sc.nextInt(); // scanning no. of elements
int[] array = new int[arraySize];
for (int j = 0; j < arraySize; j++) {
array[j] = sc.nextInt();
}
while (array.length > 2) {
cost = cost + getResultForLocation(array, 1);
array = reduceArray(array, 1);
}
}
System.out.println(cost);
}
static int getResultForLocation(int[] array, int location) {
int cost = 0;
if (location > 0 && location < array.length - 1) {
// logic part
cost = cost + (array[location] * array[location - 1]) + (array[location] * array[location + 1]) + (array[location - 1] * array[location + 1]);
}
return cost;
}
static int[] reduceArray(int[] array, int locationToRemove) {
if (array == null || array.length <= 2) {
return array;
}
if (locationToRemove == array.length) {
return array;
}
int[] returnArray = new int[array.length - 1];
for (int i = 0; i < locationToRemove; i++) {
returnArray[i] = array[i];
}
for (int i = locationToRemove; i < array.length - 1; i++) {
returnArray[i] = array[i + 1];
}
return returnArray;
}
方法getResultForLocation计算位置x中元素的成本(如果它是合法位置),然后返回它。
方法reduceArray删除位置x的元素并返回一个较小的数组。
在主要部分中,我构建了一个累积可能性 - 从第一个符合条件的位置开始,计算成本,删除项目 - 并重复直到数组减少到两个成员,累积每一步的成本。此处显示的数组的结果是 30。
在控制台中输入数字: 1 4 1 2 3 4
结果是 30
关于java - 删除数组的相邻元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569279/