一个数组,里面是1——1000的整数,除了1以外的其他数都不能重复,其中1能代表任何数,求问数组a是否是连续的,如,a[5]={4,2,3,1,5}为连续,a[5]={2,3,5,4,7}为不连续
package xinlang;
import java.util.SortedSet;
import java.util.TreeSet;
public class XinLang1 {
public static int[] a = {4,2,3,1,6,9,1};
private boolean isLinked() {
int count1 = 0;
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i=0; i < a.length; ++i) {
if (a[i] == 1) {
count1 ++;
continue;
}
set.add(a[i]);
}
int first = set.first();
set.remove(first);
while (set.size() != 0) {
int tmp = set.first();
int sub = tmp - first;
if (sub == 1) {
first = tmp;
set.remove(first);
continue;
}
count1 = count1 - sub + 1;
if (count1 < 0) {
return false;
}
first = set.first();
set.remove(first);
}
return true;
}
public static void main(String[] args) {
XinLang1 xl = new XinLang1();
System.out.println(xl.isLinked());
}
}
欢迎指正~