×

Loading...

my code:

zhouziren1 (zhouziren)
本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
public class ASeries {
public static final int MIN_VALUES_LENGTH=2;
public static final int MAX_VALUES_LENGTH=50;
public static final int MIN_VALUE=-1000000;
public static final int MAX_VALUE=1000000;

public static void main(String[] args) throws Exception {
ASeries as=new ASeries();
System.out.println("res:"+as.longest(new int[] {3,8,4,5,6,2,2}));
}

public int longest(int[] values) throws Exception {
int ret=2;
if ( values == null || values.length < MIN_VALUES_LENGTH || values.length > MAX_VALUES_LENGTH ) {
throw(new Exception("values is null or has invalid amount of elements!"));
}
Arrays.sort(values);
if ( values[0] < MIN_VALUE || values[values.length-1] > MAX_VALUE ) {
throw(new Exception("At least one value is out of the range!"));
}
if ( values.length == 2 ) {
ret=2;
return ret;
}
int[] valuesDiff=new int[values.length-1];
for ( int i=1 ; i<values.length ; i++ ) {
valuesDiff[i-1]=values[i]-values[i-1];
}
int[] repeatCnt=new int[valuesDiff.length-1];
for ( int i=0 ; i<valuesDiff.length-1 ; i++ ) {
int tmpCount=1;
for ( int j=i+1 ; j<valuesDiff.length ; j++ ) {
if ( valuesDiff[j] == valuesDiff[i] ) {
tmpCount++;
}
}
repeatCnt[i]=tmpCount;
}
Arrays.sort(repeatCnt);
ret=repeatCnt[repeatCnt.length-1]+1;
return ret;
}

}
更多精彩文章及讨论,请光临枫下论坛. 网址: rolia.net/zh
(#9938278@0)
2016-2-10 -05:00
Reply
Page address has been copied.
To share, click to copy page address.
Share Online by QR Code

Back To Topic: 一道面试题,大家给出出主意哈,我一点头绪都没有

Back To Forum: HOME枫下论坛枫下论坛主坛工作学习学科技术