寻找所有长度为n的子list集合

寻找所有长度为n的子list集合

/**

  • 给定一个正整数不重复有序数组,一个连续数值长度number,找出数组中所有长度为number的连续数组, 元素可重复出现在不同组合中
  • ex:
  • list : 1, 2, 3, 5, 6
  • number : 2
  • out:
  • [1, 2], [2,3], [5,6]
  • ???如果给定的是无序数组呢???
    */

import java.util.*;

public class FindGroup {
	public static void main(String[] args){
    	System.out.println("hello");
    	List<Integer> list1 = new ArrayList(Arrays.asList(1, 2, 3, 5, 6, 7, 11, 12, 9));
    	List<Set<Integer>> temp = getConnectionGroup(list1, 2);
    	for (Set<Integer> t : temp){
        	System.out.println(t);
    	}
	}



public static List<Set<Integer>> getConnectionGroup(List<Integer> list, int number) {
    //获取list中所有连续的数size = number  的组合
    List<Set<Integer>> result = new ArrayList<>();
    if (list.size() < number){
        return result;
    }
    Collections.sort(list);
    List<Integer> tempGroup = new ArrayList<>();
    for (int i=0; i<list.size() ; ++i){
        if (tempGroup.size() == 0){
            tempGroup.add(list.get(i));
        }
        else{
            if (tempGroup.size() < number){
                //相邻,加入group
                if (list.get(i) - tempGroup.get(tempGroup.size() -1 ) != 1){
                    tempGroup = new ArrayList<>();
                }
                tempGroup.add(list.get(i));
            }else {
                Set<Integer> temp = new HashSet<>(tempGroup);
                result.add(temp);
                //相邻,移除第一个元素,加入group
                if (list.get(i) - tempGroup.get(tempGroup.size() -1 ) == 1){
                    tempGroup.remove(0);
                }else {
                    tempGroup = new ArrayList<>();
                }
                tempGroup.add(list.get(i));
            }
        }
    }
    if (tempGroup.size() == number){
        result.add(new HashSet<>(tempGroup));
    }
    return result;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值