1. 程式人生 > >整型數組——首尾相連

整型數組——首尾相連

method play clas for 出現 static 獲得 i++ 基礎

上次的數組代碼基礎上,增加要求,數組首尾相連輸出最大子數組,例如 1,1,-5,1,1獲得的最大子數組應為:1,1,1,1;不是1,1;

初步想法為新建數組,將原來的數組加到末尾獲得新的更長的數組。

技術分享圖片
package shuzu;
import java.util.Scanner;
public class shuzu2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
             Scanner sc = new Scanner(System.in);
                
int[] a = new int[5]; int[] b= new int[10]; // 控制臺輸入數組值 for (int i = 0; i < a.length; i++) { System.out.println("請輸入第" + (i + 1) + "個數字:"); int num = sc.nextInt(); a[i] = num; b[i]
=num; } sc.close(); for(int j=0;j<b.length-5;j++) { b[j+5]=a[j]; } int max=a[0]; int sum=a[0]; for(int i=1;i<(b.length-1);i++) { if(sum<0) sum
=b[i]; else sum+=b[i]; if(sum>max) max=sum; } System.out.println(max); } }
View Code

新的代碼中存在的問題:

沒有判斷子數組的長度不能超出原數組長度

一旦數組中都為整數或負數較小會出現錯誤。

解決辦法:

控制子數組長度,最大長度設置為原數組長度,超出則結束。

整型數組——首尾相連