【转发】java-数组分组算法

代码示例如下:

public class LeetCode {
	public static void main(String[] args) {
		String[] elements = {"1","8","3","4","5","6","7","8","9","10"};
		List<String[]> list = groupBySequence(4,elements);
		for(String[] strs : list) {
			for(int i=0;i<strs.length;i++) {
				System.out.print(strs[i]+"  ");
			}
			System.out.println();
		}
	}

	private static List<String[]> groupBySequence(int gc, String[] elements) {
		List<String[]> list = new ArrayList<>();
		int count = elements.length / gc;
		int mod = elements.length % gc;
		if (mod != 0)
			count++;
		for (int i = 0; i < count; i++) {
			String[] arr;
			if (i == (count - 1)) {
				if (mod != 0) {
					int temp = 0;
					arr = new String[mod];
					for (int j = i * gc; j < (i * gc) + mod; j++) {
						arr[temp] = elements[j];
						temp++;
					}
				} else {
					int temp = 0;
					arr = new String[gc];
					for (int j = i * gc; j < gc * (i + 1); j++) {
						arr[temp] = elements[j];
						temp++;
					}
				}
			} else {
				int temp = 0;
				arr = new String[gc];
				for (int j = i * gc; j < gc * (i + 1); j++) {
					arr[temp] = elements[j];
					temp++;
				}
			}
			list.add(arr);
		}
		return list;
	}
}

你可能感兴趣的:(java,Java,数组分组)