面试题整理4
给定一个int数组,写一个函数判断该数组中的所有数字是否能组成连续数字。如[1,3,4,6,2,5]能组成连续数字,【1,2,5,4,7】不能
另外,情况1,重复数字算可连续数组.
情况2,重复数字不算可连续数组.
?
?
-------------------
public static void main(String[] args) {
??int[] num = new int[]{3,1,4,2,5,3};
//??check1(num);
??check2(num);
?}
?//1
?public static void check1(int[] num){
??Arrays.sort(num);
??for(int i=1; i<num.length;i++){
???if(num[i]!=num[0]+i){
????System.out.println(num+"不是可连续数字");
????break;
???}
??}
?}
?//1
?public static void check2(int[] num){
??int max = num[0],min=num[0],same=num[0],length=num.length;
??boolean result = true;
??for(int i=1;i<num.length;i++){
???if(num[i]>max) max=num[i];
???if(num[i]<min) min=num[i];
???if(same==num[i]) {
????length -= 1;
????result = false;
???}
??}
??if(max-min+1!=length||!result){
???System.out.println(num+"不是可连续数字");
??}
?}
?
?//2
?public static void check3(int[] num){
??int max = num[0],min=num[0],same=num[0],length=num.length;
??for(int i=1;i<num.length;i++){
???if(num[i]>max) max=num[i];
???if(num[i]<min) min=num[i];
???if(same==num[i]) {
????length -= 1;
???}
??}
??if(max-min+1!=length){
???System.out.println(num+"不是可连续数字");
??}
?}