Java程序 将两个列表中的对应元素相乘

Java程序 将两个列表中的对应元素相乘

两个对应的元素相乘意味着将一个列表的第一个元素与另一个列表的第一个元素相乘,然后再与第二个元素相乘,直到列表的大小。给定两个列表的元素,我们必须将两个列表的相应元素相乘。

这可以通过2种方式进行。

1.使用额外的空间
2.不使用额外空间

方法1:(使用额外空间)- 并在最后打印该字符串。

// Java program to multiply the corresponding elements of
// two list. using string in-built function
  
import java.util.Arrays;
  
class GFG {
    public static void main(String[] args)
    {
        int a1[] = { 2, 5, -2, 10 };
        int a2[] = { 3, -5, 7, 1 };
  
        String result = "";
  
        for (int i = 0; i < a1.length; i++) {
            // converting integer to string and
            // multiplying corresponding element
            result += Integer.toString(a1[i] * a2[i]) + " ";
        }
  
        System.out.println(result);
    }
}

输出

6 -25 -14 10

空间复杂度: O(n)

现在,如果我们想在以后的程序中使用结果,我们也可以将输出存储在新的数组中,而不是使用字符串。

// Java program to cmultiply the corresponding elements of
// two list. using new array
  
import java.util.Arrays;
  
class GFG {
    public static void main(String[] args)
    {
        int a1[] = { 2, 5, -2, 10 };
        int a2[] = { 3, -5, 7, 1 };
  
        int result[] = new int[a1.length];
  
        for (int i = 0; i < a1.length; i++) 
        {
            // multiplying corresponding element
            result[i] = a1[i] * a2[i];
        }
  
        for (int i = 0; i < a1.length; i++)
        {
            System.out.print(result[i] + " ");
        }
    }
}

输出

6 -25 -14 10

空间复杂度: O(n)

方法 2: (不使用额外空间)

这和上面提到的方法是一样的。唯一不同的是,我们不使用额外的数组,而是使用输入的两个数组中的任何一个来存储输出或乘法后的值。

// Java program to multiply the corresponding elements of
// two list. using no extra space
  
import java.util.Arrays;
  
class GFG {
    public static void main(String[] args)
    {
        int a1[] = { 2, 5, -2, 10 };
        int a2[] = { 3, -5, 7, 1 };
  
        for (int i = 0; i < a1.length; i++) {
            
            // multiplying corresponding element
            // you can use any array
            a1[i] = a1[i] * a2[i];
        }
  
        for (int i = 0; i < a1.length; i++) {
            System.out.print(a1[i] + " ");
        }
    }
}

输出

6 -25 -14 10

空间复杂度: O(1) (因为我们不使用任何其他的辅助空间)

注意: 上述所有代码的时间复杂度为O(n)。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程