遍历两次,一个个相乘,选出最大数(时间复杂度高)
package com.test6;
public class MaxIndex {
public static void main(String[] args) {
int[] nums = {3,4,5,2};
int m =maxProduct(nums);
System.out.println("数组中两元素最大乘机为"+m);
}
public static int maxProduct(int[] nums) {
int max = 0;
int count = 0;
for(int i=0;i<nums.length;i++){
for(int j = 0;j<nums.length;j++){
if(i!=j) {
count = (nums[i] - 1) * (nums[j] - 1);
max= max>count?max:count;
// System.out.println(count);
}
}
}
return max;
}
}
官方解法:
直接调用排序方法,那么索引的最后两位就是俩个最大值了
Arrays.sort(nums);
return (nums[nums.length-1]-1)*(nums[nums.length-2]-1);
将0,1索引处的值与后面一次比较,将小值替换为大值
class Solution {
public int maxProduct(int[] nums) {
int a = nums[0], b = nums[1];
if (a < b) {
int temp = a;
a = b;
b = temp;
}
for (int i = 2; i < nums.length; i++) {
if (nums[i] > a) {
b = a;
a = nums[i];
} else if (nums[i] > b) {
b = nums[i];
}
}
return (a - 1) * (b - 1);
}
}