【问题标题】:Removing and adding items to an array?删除和添加项目到数组?
【发布时间】:2014-12-23 08:25:53
【问题描述】:

我正在尝试编写一个接收数字数组的方法。如果数组中有任何零,它将添加另一个零,但数组必须保持相同的长度,以便从新数组中删除最后一个数字。这是我已经开始做的事情,但我认为它不会有任何进展。

public static int[] MoveToRightOne(int userArray[] ) 
{ 
    int newArray [] = new int[userArray.length + 1]; 
    int zero = 0; 
    for(int i = 0; i < userArray.length; i++) 
    { 
        if (userArray[i] == 0) 
            zero = zero + 1; 
        newArray[i + zero] = userArray[i - 1]; 
    } 

    return(userArray); 
}

【问题讨论】:

  • 建议:告诉我们您使用的是什么语言?
  • 评论!请添加 cmets 描述您的代码的每个部分打算做什么。
  • 我不太明白该方法的目标。如果有 any 零,它只是用零替换数组的最后一个元素吗?或者它是否为数组中的每个零添加一个零?如果是这样,那么它们将添加到数组的哪个索引?
  • 它在数组中的每个零实例之后添加一个零。所以为了保持数组的原始长度,它从末尾删除整数。这是一个输入和输出示例:“1 2 0 3 0 4 0 5 0 6 6 0 0”“1 2 0 0 3 0 0 4 0 0 5 0 0”

标签: java arrays


【解决方案1】:

以下代码将满足您的目的

public static int[] MoveToRightOne(int userArray[] ) { 
    int newArray [] = new int[userArray.length];
    for(int i = 0, j = 0;j < userArray.length;i++,j++){
        newArray[j] = userArray[i];
        if(userArray[i] == 0 && j+1 < userArray.length){
            j ++;
            newArray[j] = 0;
        }
    }  
    return(newArray); 
}

【讨论】:

  • 如果userArray[i] == 0j == userArray.length - 1; 这将不起作用它会增加它并尝试插入超出范围的newArray[userArray.length]
【解决方案2】:

我想这会做你想要的

public static int[] MoveToRightOne(int userArray[] ) {
    // the new array will have the same length as the input 
    int newArray [] = new int[userArray.length]; 
    // two indexes i for the input and j for the output
    int i = 0, j = 0;
    while(j < userArray.length){ // while it's not the end of the output
        // we insert the element
        newArray[j] = userArray[i];
        if(userArray[i] == 0){ // if the current element is a 0
            // we insert an additional 0
            j ++;
            if(j < userArray.length)
                newArray[j] = 0;
        }
        // increment indexes
        i ++;
        j ++;
    }
    return newArray; 
}

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2017-01-29
    • 1970-01-01
    • 2015-09-18
    • 2017-09-13
    • 2018-09-19
    • 2019-11-30
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多