第二周个人作业--数组
定义一个整型数组,返回该数组中子数组和的最大值!
思路:
先定义一个数组,随机生成一个数组并输出;
再通过两个for循环嵌套去计算每个子数组的值并进行最大值的比较;
package zuoye_01;
import java.util.Random;
public class shuzu {
public static void main(String[] args) {
Random random=new Random();
int a[] = new int[10];//随机数组
System.out.print("随机数组:");
for(int i = 0 ; i < 10 ; i++) {
a[i] = random.nextInt(20)-10;
System.out.print(a[i]+" ");
}
System.out.print("\n");
int Max = a[0];//最大值
for(int m = 0 ; m < 10 ; m++) {
int sum = a[m];//和
for(int n = m + 1 ;n < 10 ;n++ ) {
if(Max < a[n]) Max = a[n];
sum = sum + a[n];
if(Max <= sum) Max = sum;
}
}
System.out.println("最大值是:"+Max);
}
}

问题:
不能做到时间复杂度是O(n)
解决方案:无
整体总结:
方法比较老,去借鉴一下别人的方法,看是否能有新的方法做出来。

浙公网安备 33010602011771号