public int dominantIndex(int[] nums) {
int index = 0;//nums最大值的索引
if (nums.length == 1) {//当长度为1时
return index;
}
int max = nums[0];//设nums中的最大值
for (int i = 0;i < nums.length;i ++) {//nums长度不为1,循环找最大值和相应的索引
if (max < nums[i]) {
int temp = max;
max = nums[i];
nums[i] = temp;
index = i;
}
}
for (int i = 0;i < nums.length;i ++) {//循环查看最大值是否符合要求
if (max < 2*nums[i] && i != index) {
index = -1;
}
}
return index;
}
你选取最大的index时候把做了位置变换,把数据丢了。去掉交换数据的三行。或者可以在选择最大值的时候就比较了
对了,但是还是不明白交换数据,为什么索引没有赋到
for (int i = 0;i < nums.length;i ++) {//nums长度不为1,循环找最大值和相应的索引
if (max < nums[i]) {
int temp = max;
max = nums[i];
nums[i] = temp;
index = i;
}
上面的交换数据把改变了数组原始值(楼上也提到了),即由[0,0,2,3]变成了[0,0,0,2],所以执行
if (max < 2*nums[i] && i != index) {
index = -1;
}
if判断一直为false,index=-1无法执行到。
可以把获取最大值中的nums[i] = temp;注释掉,即//nums[i] = temp;
这只是遍历数组查找最大值,怎么把数组原来的数据都变了。