本文发表在 rolia.net 枫下论坛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
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