这个题,用Java语言解决。我还没学其他的方法,用的比较初始的办法。首先写个方法,找到该数组a的最大元素的下表,然后在拷贝一个新的数组b,将其升序排列。接下来最重要的的点
1.判断拷贝数组b的长度是否大于1,等于1的话,就输出原数组
a的最大元素下标;
2,如果长度大于1,然后就要用升序后的数组倒数第一位元素除倒数第二位的元素;
3,此时注意,判断倒数第二为的元素是否为0 ,如果是零的话,最后那个元素(数组最大的值)肯定是其他元素的二倍还要多;
4,如果倒数第二位元素不是0;就判断最大的元素是不是其二倍之多,是的话就存在,同上;
5,如果不是二倍之多,说明就不存在该元素,输出-1;
代码如下:
public class TestYu {
public static int dominantIndex(int[] nums) {
int[] copy = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
copy[i] = nums[i];
}
Arrays.sort(copy);
if (copy.length == 1 ) {
return -1;
}
if (copy[copy.length - 2] < 0) {
return max(nums);
} else if (copy[copy.length - 1] / copy[copy.length - 2] < 2) {
return -1;
}
return max(nums);
}
public static void main (String[] args) {
int[]nums = {0,1,0,4};// 可以给任意值;
System.out.println(dominantIndex(nums));
}
public static int max (int[] nums){
int max = 0;
int count = 0;
for (int j = 0; j < nums.length; j++) {
if( max < nums[j]){
max = nums[j] ;
count = j;
}
}
return count ;
}
}