题目:寻找一个数组中连续几个元素,和为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)); } } } }