我试图在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;
}
有什么问题吗?
我试图在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;
}
有什么问题吗?
当前回答
private static int[] reverse(int[] array){
int[] reversedArray = new int[array.length];
for(int i = 0; i < array.length; i++){
reversedArray[i] = array[array.length - i - 1];
}
return reversedArray;
}
其他回答
public void display(){
String x[]=new String [5];
for(int i = 4 ; i > = 0 ; i-- ){//runs backwards
//i is the nums running backwards therefore its printing from
//highest element to the lowest(ie the back of the array to the front) as i decrements
System.out.println(x[i]);
}
}
public class TryReverse {
public static void main(String[] args) {
int [] array = {2,3,4,5,6,7,8,9};
reverse(array);
for(int i=0; i<array.length; ++i)
System.out.print(array[i] + " ");
}
public static void reverse (int [] array){
for(int start=0, end=array.length-1; start<=end; start++, end--){
int aux = array[start];
array[start]=array[end];
array[end]=aux;
}
}
}
我认为如果你声明显式变量来跟踪你在每次循环迭代中交换的下标,那么遵循算法的逻辑会更容易一些。
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
我还认为在while循环中执行这个操作更具可读性。
public static void reverse(int[] data) {
int left = 0;
int right = data.length - 1;
while( left < right ) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// move the left and right index pointers in toward the center
left++;
right--;
}
}
public static int[] reverse(int[] array) {
int j = array.length-1;
// swap the values at the left and right indices //////
for(int i=0; i<=j; i++)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
j--;
}
return array;
}
public static void main(String []args){
int[] data = {1,2,3,4,5,6,7,8,9};
reverse(data);
}
在Java 8的情况下,我们还可以使用IntStream来反转整数数组:
int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
.toArray(); //Output: [5, 4, 3, 2, 1]