題目:尋找一個數組中連續幾個元素,和為0,且這幾個元素為這個數組中連續個數最多的幾個元素,并且輸出打印這些元素。
輸入樣例:
1 2 3 0 -3 -2 1
1 2 3 0 -3 -2 1 0 -2 -3 2 3
輸出樣例:
2 3 0 -3 -2
1 2 3 0 -3 -2 1 0 -2 -3 2 3
------------------------------------------------I am a Dividing line---------------------------------------------
java代碼:
import java.util.ArrayList;import java.util.List;import java.util.Scanner;/** * 連續子數組和為0的最大個數 * * @author ForeverLover * */public class ArrayLine { public static void main(String[] args) { while (true) { // ---------------輸入-----------------// Scanner scan = new Scanner(System.in); String s = scan.nextLine(); String[] sa = s.split(" "); int[] array = new int[sa.length]; for (int i = 0; i < array.length; i++) array[i] = Integer.parseInt(sa[i]); // --------------尋找數組------------------// List<Integer> list = new ArrayList<Integer>(); List<Integer> result = new ArrayList<Integer>(); for (int i = 0; i < array.length; i++) { int sum = array[i]; result.clear(); result.add(array[i]); for (int j = i + 1; j < array.length; j++) { if ((sum += array[j]) == 0) { result.add(array[j]); if (result.size() >= list.size()) { list.clear(); list.addAll(result); } } else result.add(array[j]); } } // ---------------輸出------------------// for (int i = 0; i < list.size(); i++) { if (i != list.size() - 1) System.out.PRint(list.get(i) + " "); else System.out.println(list.get(i)); } } }}
新聞熱點
疑難解答