牛客网刷题日记最大乘积

最大乘积

要求时间复杂度,为O(n),空间发杂度O(1)

import java.util.*;
import java.lang.Math.*;
public class Main{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int num=Integer.parseInt(sc.nextLine());
        String arrStr=sc.nextLine();
        String arr[]=arrStr.split("\\s+");
        //int list[]=new int[arr.size()];
        int min1=Integer.MAX_VALUE,min2=Integer.MAX_VALUE,max1=Integer.MIN_VALUE
            ,max2=Integer.MIN_VALUE,max3=Integer.MIN_VALUE;
        if(num<3){
            System.out.println(0);
        }
        for(int i=0;i<num;i++)
        {
           int temp=Integer.valueOf(arr[i]);
            if(temp>max1)
            {
               max3=max2;
               max2=max1;
                max1=temp;
                
            }else if(temp>max2){
                max3=max2;
                max2=temp;
            }else if(temp>max3){
                max3=temp;
            }
            if(temp<min1){
                min2=min1;
                min1=temp;
            }else if(temp<min2){
                min2=temp;
            }
                
        }
       // if(arr.size()<3)
       
            long res=Math.max((long)max1*min1*min2,(long)max1*max2*max3);
        System.out.print(res);
    }
}

这里犯得错误,对于忽略最大和最小数重合的问题,所以在判断的时候,全是else if,其实在求最小值的时候,也是要遍历每一个数字的,而不是判断是否产生最大值之后就不再判断是否产生最大值,另外就是在初始化最大最小值得收没有用整数最大值和整数最小值,而是用0判断,这样如果最大的三个中有小于0的数时,将产生错误。还有就是,需要将结果转为long型,否则,也会产生错误的结果。
这里在复习一下,java提供8种数据类型,java的基本数据类型:

  1. byte:占8位,有符号,以二进制补码表示;
  2. short:16位;
  3. int:32位有符号;
  4. long:64位,有符号;
  5. float:32位浮点数
  6. doubl:64位双精度
  7. boolean:1位
  8. char:16为Unicode.

.

猜你喜欢

转载自blog.csdn.net/qq_30035749/article/details/88384622