从今天开始记录一下在力扣上面的题目,希望每天能够坚持刷一道!
题目难度:简单
题目描述:
给你一个非负整数数组 nums 。如果存在一个数 x ,使得 nums 中恰好有 x 个元素 大于或者等于 x ,那么就称 nums 是一个 特殊数组 ,而 x 是该数组的 特征值 。
注意: x 不必 是 nums 的中的元素。
如果数组 nums 是一个 特殊数组 ,请返回它的特征值 x 。否则,返回 -1 。可以证明的是,如果 nums 是特殊数组,那么其特征值 x 是 唯一的 。
解决思路:蛮力法,让x依次以不同值和数组里面的数比对即可,用count来记录大于或者等于的个数。
代码:import java.util.Scanner;
public class codeOne{
public int specialArray(int[] nums) {
for(int i=0;i<nums.length+1;i++) {
int count=0;
for(int j=0;j<nums.length;j++) {
if(i<=nums[j]) {
count++;
}
}
if(count==i) {
return i;
}
}
return -1;
}
public static void main(String args[]) {
codeOne x=new codeOne(); //main中调用非静态方法需要创建实例对象
Scanner sc = new Scanner(System.in);
String str = sc.next().toString();
String[] arr = str.split(",");
int[] b = new int[arr.length];
for(int j = 0; j<b.length;j++) {
b[j] = Integer.parseInt(arr[j]);
}
System.out.println(x.specialArray(b));
}
}