我试图在Java中反转一个int数组.
此方法不会反转数组.
for(int i = 0; i < validData.length; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
Run Code Online (Sandbox Code Playgroud)
这有什么问题?
如果我有这样的数组:
1 4 9 16 9 7 4 9 11
Run Code Online (Sandbox Code Playgroud)
反转数组的最佳方法是什么,使它看起来像这样:
11 9 4 7 9 16 9 4 1
Run Code Online (Sandbox Code Playgroud)
我有下面的代码,但我觉得这有点单调乏味:
public int[] reverse3(int[] nums) {
return new int[] { nums[8], nums[7], nums[6], nums[5], num[4],
nums[3], nums[2], nums[1], nums[0] };
}
Run Code Online (Sandbox Code Playgroud)
有更简单的方法吗?
我试图扭转java中数组的顺序.
在O(n)中使用最少内存量的最有效方法是什么.
无需用代码回答,伪代码就行了.
这是我的思考过程:
create a new temp array //I think this is a waste of memory,
//but I am not sure if there's a better way
grab elements from the end of the original array -decrement this variable
insert element in beginning of temp array -increment this variable
then make the original array point to the temp array? //I am not sure
//if I can do this in java; so let's say the
//original array is Object[] arr; and …Run Code Online (Sandbox Code Playgroud)