我的代码只有5种情况,我不知道为什么,谁来帮我。
问题
返回给定数组的一个版本,其中数组中的每个零值被数组中的最大奇数替换为数组中的零的右边。如果在零的右边没有奇数值,则将零保留为零。 zeroMax({0,5,0,3})→{5,5,3 } zeroMax({0,4,0,3})→{3,4,3,3} zeroMax({0,1,0})→{1,1,0}
我的代码
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for( i = 0; i < nums.length;i++){
if(nums[i]==0){
for(int j = i; j < nums.length;j++){
if (nums[j]%2!=0){
acum = nums[j];
break;
}
}
nums[i]=acum;
}
}
return nums;
}发布于 2015-06-15 22:59:35
你所缺少的是,在你的零的右边可能有一个以上的奇数,你需要选择最大的一个。
编辑:和你也需要重置'acum‘。我更新了我的建议:
以下是一个建议:
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
for (int j = i; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > acum) {
acum = nums[j];
}
}
nums[i] = acum;
acum = 0;
}
}
return nums;
}发布于 2015-06-16 00:05:13
通过稍微调整一下问题,可以更有效地完成这一任务。
与其从左向右遍历,然后扫描右边的整数以进行替换,不如从右向左移动。然后,您可以存储以前的替换,直到遇到更大的奇数。
public int[] zeroMax(final int[] nums) {
int replace = 0; // Stores previous largest odd - default to 0 to avoid replacement
for (int i = nums.length - 1; i >= 0; i--) { // start from end
final int next = nums[i];
if (next == 0) { // If we should replace
nums[i] = replace;
} else if (next % 2 == 1 && next > replace) {
// If we have an odd number that is larger than the replacement
replace = next;
}
}
return nums;
}给出你的例子,这个输出:
[5, 5, 3, 3]
[3, 4, 3, 3]
[1, 1, 0]发布于 2019-07-13 03:37:32
public int[] zeroMax(int[] nums) {
for (int i=0; i<nums.length; i++)
{
if (nums[i] == 0)
{
int maxindex = i;
for (int j=i+1; j<nums.length; j++)
{
if ((nums[j]%2 == 1) && (nums[j] > nums[maxindex]))
{
maxindex = j;
}
}
nums[i] = nums[maxindex];
}
}
return nums;
},这将分配您在右边找到最大奇数的索引,用该索引的数字替换为零。
https://stackoverflow.com/questions/30856244
复制相似问题