【问题标题】:Moving number to the end in an array [duplicate]将数字移动到数组的末尾[重复]
【发布时间】:2013-03-01 16:45:46
【问题描述】:

下面的代码我已将数组的中点设置为 5,但现在我想将中点移动到最后,当它移动到最后时,其他数字将向左移动以填补空白。没有数组列表大声。

        int mid = length/2;

    for (int i = array.length-1 ; i> mid; i--) { 
        array[i] = array[i-1]; 
    } 
    array[mid] = 5;

【问题讨论】:

  • @UmNyobe 将中点移到末尾,同时将数组中的其他数字向左移动
  • 该代码将数字 5 放在中间点。我真的不知道为什么。当你说结束时,你的意思是数组中的最后一个位置吗?正如@Che 所说,您尝试过什么?
  • 你需要一个swapElement(int ndx1, int ndx2)操作,这听起来像是功课?
  • 可悲的是,通过在他们不断发布此人之后为他们做作业,人们鼓励了这种行为。

标签: java arrays


【解决方案1】:

这样的?

int mid = array.length/2;

for (int i = mid; i < array.length-1; i++)
{
    int temp = array[i];
    array[i] = array[i+1];
    array[i+1] = temp;
}

【讨论】:

    【解决方案2】:
    public static void main(String[] args) {
        int array[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int mid = array.length / 2;
        array[mid] = 5;
    
        // my code starts here...
    
        int aux = mid; // aux isn't necessary if you can lost mid value
        int backup = array[mid]; // save the middle value
    
        for (; aux < array.length - 1; aux++) { //starting at middle until the end of array
            // current pos receives the next value;
            array[aux] = array[aux + 1];
        }
    
        array[array.length - 1] = backup; // restore the middle value at the end;
    }
    

    该代码将 [1, 2, 3, 4, 5, 6, 7, 8, 9] 转换为 [1, 2, 3, 4, 6, 7, 8, 9, 5]。 是你想要的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多