int[] big = {1,2,3,5,11,12,13,25,26};
doSomething将连续的元素组合在一起 如何将“大”分成这个:
{{1,2,3},{5},{11,12,13},{25,26}}
我已经开始使用此代码了:
public List<Integer> getR(){
Integer[] big = {1,2,3,5,11,12,13,25,26};
List<Integer> a = new ArrayList<Integer>();
for(int i=0;i<big.length;i++){
if(big[i]==big[i+1]-1){
continue;
}else{
//...
}
//...
}
//...
}
答案 0 :(得分:8)
我可以给你伪代码。
现在你有阵列了。如果一切都已经连续,那么你基本上已经为第一个数组创建了一个副本。
答案 1 :(得分:2)
结果数组是一个二维数组,Java中允许使用以下内容。
int[][] split = new int[4][];
split[0] = new int[3];
split[1] = new int[1];
split[1] = new int[3];
split[1] = new int[2];
//note: you can use variables instead integer values (like 4, 3, 2, ...) here
您可以利用该信息来形成新阵列。
<强>更新强>
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> curr = null;
for (int i = 0; i < big.length; i++) {
if(i == 0 || (big[i] != big[i-1]+1)) {
//if the current element is the first element or doesn't satisfy the condition
curr = new ArrayList<Integer>(); //create a new list and set it to curr
result.add(curr); //add the newly created list to the result list
}
curr.add(big[i]); //add current element to the curr list
}
答案 2 :(得分:2)
这是一种按连续大小排序数组的方法,以及测试它的主要方法:
public static void main(String[] args) {
int[] big = {1,2,3,5,11,12,13,25,26};
try {
System.out.println(Arrays.deepToString(splitContiguous(big, 3, 1, 3, 2)));
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int[][] splitContiguous(int[] original, int... ranges) throws Exception {
if (original.length == 0 || ranges.length == 0 || ranges.length > original.length) {
throw new Exception("TODO handle some mess...");
}
int[][] result = new int[ranges.length][];
int rangesIndex = 0;
int index = 0;
for (int range: ranges) {
result[rangesIndex] = new int[range];
for (int i = 0; i < range; i++) {
result[rangesIndex][i] = original[index];
index++;
}
rangesIndex++;
}
return result;
}
输出:
[[1, 2, 3], [5], [11, 12, 13], [25, 26]]
答案 3 :(得分:0)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class testSth {
public List<List<Integer>> getR(){
Integer[] big = {1,2,3,5,11,12,13,25,26};
List<Integer> a = Arrays.asList(big);
List<List<Integer>> all = new ArrayList<List<Integer>>();
for(int i=0;i<a.size();i++){
List<Integer> b = new ArrayList<Integer>();
if(a.get(i)==a.get(i+1)-1){
b.add(a.get(i));
}else{
b.add(a.get(i));
all.add(b);
}
}
return all;
}
}
答案 4 :(得分:0)
根据Mena的回答还有另一个答案
int[] flag=new int[big.length];
int j=0;
flag[0]=0;
for(int i=1;i<big.length;i++){
if(!big[i-1]+1==big[i]) j++;
flag[i]=j;
}
输出将是:0 0 0 1 2 2 2 3 3,比你可以看到它还可以解决这个问题