这是我的数组:
int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
假设我想将 myArray[3](它可以是任何元素)和 myArray[6](与这个相同)移动到数组的前面,同时重新排列后面,我该怎么做?示例:
这个:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
进入这个:
{3, 6, 0, 1, 2, 4, 5, 7, 8, 9}
最佳答案
要将索引 x
移到前面,您需要:
- 记住索引
x
的内容 - 复制从
0
到x - 1
的所有内容向上一个索引,例如使用System.arrayCopy
- 将索引
0
处的值设置为您在第一步中记住的值
例如:
public void moveToHead(int[] values, int index)
{
// TODO: Argument validation
int value = values[index];
System.arraycopy(values, 0, values, 1, index - 1);
values[0] = value;
}
请注意 System.arraycopy
适本地处理复制:
If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.
您的原始示例提到了两个元素 - 虽然您可以提前知道这两个元素,但可以更有效地完成所有这些操作,将其建模为两个 moveToHead< 会简单得多
调用。您需要注意顺序 - 例如,如果您想先将索引 6
移动到头部,则需要移动索引 4 而不是索引 3,以考虑到第一步。
关于Java根据元素编号重新排列数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8572038/