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