1. 题目描述
Given an integer array, find if an integer p exists in the array such that the number of integers greater than p in the array equals to p
If such an integer is found return 1 else return -1.
在一个整形数组中,如果存在一个元素p使得数组中大于p的元素个数刚好为p,则返回1, 否则返回-1.
2. 解法
package com.fqyuan.arrays;
import java.util.ArrayList;
import java.util.Collections;
/*
* Given an integer array, find if an integer p exists in the array,
* such that the number of integers greater than p in the array equals to p
* If such an integer is found return 1 else return -1.
*/
public class NobleInteger {
public int solve(ArrayList<Integer> A) {
Collections.sort(A);
for (int i = 0; i < A.size(); i++) {
if (A.get(i) == A.size() - i - 1) {
if (i == A.size() - 1)
return 1;
else if (A.get(i) != A.get(i + 1))
return 1;
}
}
return -1;
}
}