美国面试题
题目:
An integer array is defined to be sequentially-bounded if it is in ascending order and each value, n, in the array occurs less than n times in the array. So {2, 3, 3, 99, 99, 99, 99, 99} is sequentially-bounded because it is in ascending order and the value 2 occurs less than 2 times, the value 3 occurs less than 3 times and the value 99 occurs less than 99 times. On the other hand, the array {1, 2, 3} is not sequentially-bounded because the value 1 does not occur < 1 times. The array {2, 3, 3, 3, 3} is not sequentially-bounded because the maximum allowable occurrences of 3 is 2 but 3 occurs 4 times. The array {12, 12, 9} is not sequentially-bounded because it is not in ascending order.
测试用例:
java 代码:
public class SequentiallyBounded {
public static void main(String[] args) {
// int[] a = {5,5,5,2,5};
// int[] a = {5,5,5,5};
// int[] a = {};
// int[] a = {0,1};
// int[] a = {-1,2};
int[] a = {5,5,5,5};
System.out.println(isSequentiallyBounded(a));
}
public static int isSequentiallyBounded(int[] a){
if(a.length>1){
int tmp = a[0];
int count =0;
for(int i=0;i<a.length-1; i++){
if(a[i]>a[i+1]){
return 0; // 满足第一个条件升序.
}
// 第二个条件
int c= 0;
for (int j = 0; j < a.length; j++) {
if(a[i]==a[j]){
c++;
}
if(a[i]<=c){
return 0;
}
}
}
}else if(a.length==1 ){
return 0;
}
return 1;
}
}