zoukankan      html  css  js  c++  java
  • 个人作业1-数组

    一、设计思路:将子数组的和挨个算出来重复利用比较。

    package shuzu;
    
    public class shuzu {
        public static void main(String[] args) {
            int [] a= {-2,-1,-2,-12,-7};
            System.out.println(max(a));
            
        }
        public static int max(int [] array) {
            int n=array.length;
            int maxSum=Integer.MIN_VALUE;
            for(int i=0;i<n;i++) {
                int sum=0;
                for( int j=i;j<n;j++) {
                    sum+=array[j];
                    if(sum>maxSum) {
                        maxSum=sum;
                    }
                    
                }
            }
            return maxSum;
            
        }
    }

    结果截图:

    总结:这套代码时间复杂度为O(n²)并没有完成任务,下面我又在网上找了一些代码,时间复杂度为O(n)比较好。代码如下

    package shuzu;
    
    public class shuzu1 {
        public static void main(String[] args) {
            int[] a= {-1,-2,-4,-8,-4,-7,-1,-5};
            System.out.println(max(a));
        }
        public static int max(int[] array) {
            int n=array.length;
            int max=0;
            int maxsum=array[0];
            for(int i = 0;i < n;i++)
            {
                if (max <= 0) {
                    max = array[i];
                }else {
                    max += array[i];
                }
                
                if (maxsum < max) {
                    maxsum = max;
                }
            }
            return maxsum;
    }
    }

    设计思路:连续数组有正有负,从首遍历 遇到负数将负数省略掉,从第一个正数开始累加 ,累加后有个判断是否小于0,若小于0,进行新的累加,最后返回最大值。

  • 相关阅读:
    IEnumerator & IEnumerable
    GameObject.Active
    Unity3D的四种坐标系
    gvim
    Platform Dependent Compilation
    delegate
    new 约束
    UIPanel
    UIButton
    UISprite
  • 原文地址:https://www.cnblogs.com/1061321925wu/p/10505952.html
Copyright © 2011-2022 走看看