如何在 Java 中反转 int 数组?

发布于 2024-08-18 19:11:58 字数 274 浏览 4 评论 0原文

我正在尝试反转 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;
}

这有什么问题吗?

I am trying to reverse an int array in Java.

This method does not reverse the array.

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;
}

What is wrong with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

时光沙漏 2024-08-25 19:11:59

时间复杂度为 o(n) ,空间复杂度为 o(1) 的解决方案。

void reverse(int[] array) {
    int start = 0;
    int end = array.length - 1;
    while (start < end) {
        int temp = array[start];
        array[start] = array[end];
        array[end] = temp;
        start++;
        end--;
    }
}

Solution with o(n) time complexity and o(1) space complexity.

void reverse(int[] array) {
    int start = 0;
    int end = array.length - 1;
    while (start < end) {
        int temp = array[start];
        array[start] = array[end];
        array[end] = temp;
        start++;
        end--;
    }
}
时光暖心i 2024-08-25 19:11:59
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 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]);
  }
}
罪#恶を代价 2024-08-25 19:11:59

这样做不是更不容易出错吗?

    int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int[] temp = new int[intArray.length];
    for(int i = intArray.length - 1; i > -1; i --){
            temp[intArray.length - i -1] = intArray[i];
    }
    intArray = temp;

Wouldn't doing it this way be much more unlikely for mistakes?

    int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int[] temp = new int[intArray.length];
    for(int i = intArray.length - 1; i > -1; i --){
            temp[intArray.length - i -1] = intArray[i];
    }
    intArray = temp;
甜心 2024-08-25 19:11:59

使用 XOR 解决方案来避免临时变量,您的代码应如下所示

for(int i = 0; i < validData.length; i++){
    validData[i] = validData[i] ^ validData[validData.length - i - 1];
    validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
    validData[i] = validData[i] ^ validData[validData.length - i - 1];
}

请参阅此链接以获得更好的解释:

http://betterexplained.com/articles/swap-two-variables-using-xor/

Using the XOR solution to avoid the temp variable your code should look like

for(int i = 0; i < validData.length; i++){
    validData[i] = validData[i] ^ validData[validData.length - i - 1];
    validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
    validData[i] = validData[i] ^ validData[validData.length - i - 1];
}

See this link for a better explanation:

http://betterexplained.com/articles/swap-two-variables-using-xor/

格子衫的從容 2024-08-25 19:11:59

反转 Array 的 2 种方法。

  1. 使用For循环交换元素直到中点,时间复杂度为O(n/2)。

    private static void reverseArray() {
    int[] 数组 = 新 int[] { 1, 2, 3, 4, 5, 6 };
    
    for (int i = 0; i < array.length / 2; i++) {
        int temp = 数组[i];
        int 索引 = array.length - i - 1;
        数组[i] = 数组[索引];
        数组[索引] = 临时;
    }
    System.out.println(Arrays.toString(array));
    

    }

  2. 使用内置函数 (Collections.reverse())

    private static void reverseArrayUsingBuiltInFun() {
    int[] 数组 = 新 int[] { 1, 2, 3, 4, 5, 6 };
    
    Collections.reverse(Ints.asList(array));
    System.out.println(Arrays.toString(array));
    

    }

    输出:[6, 5, 4, 3, 2, 1]

2 ways to reverse an Array .

  1. Using For loop and swap the elements till the mid point with time complexity of O(n/2).

    private static void reverseArray() {
    int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
    
    for (int i = 0; i < array.length / 2; i++) {
        int temp = array[i];
        int index = array.length - i - 1;
        array[i] = array[index];
        array[index] = temp;
    }
    System.out.println(Arrays.toString(array));
    

    }

  2. Using built in function (Collections.reverse())

    private static void reverseArrayUsingBuiltInFun() {
    int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
    
    Collections.reverse(Ints.asList(array));
    System.out.println(Arrays.toString(array));
    

    }

    Output : [6, 5, 4, 3, 2, 1]

山色无中 2024-08-25 19:11:59
    public static void main(String args[])    {
        int [] arr = {10, 20, 30, 40, 50}; 
        reverse(arr, arr.length);
    }

    private static void reverse(int[] arr,    int length)    {

        for(int i=length;i>0;i--)    { 
            System.out.println(arr[i-1]); 
        }
    }
    public static void main(String args[])    {
        int [] arr = {10, 20, 30, 40, 50}; 
        reverse(arr, arr.length);
    }

    private static void reverse(int[] arr,    int length)    {

        for(int i=length;i>0;i--)    { 
            System.out.println(arr[i-1]); 
        }
    }
柳絮泡泡 2024-08-25 19:11:59

对非基本类型数组使用泛型的实现。

    //Reverse and get new Array -preferred
    public static final <T> T[] reverse(final T[] array) {
        final int len = array.length;
        final T[] reverse = (T[]) Array.newInstance(array.getClass().getComponentType(), len);
        for (int i = 0; i < len; i++) {
            reverse[i] = array[len-(i+1)];
        }
        return reverse;
    }
    
    //Reverse existing array - don't have to return it
    public static final <T> T[] reverseExisting(final T[] array) {
        final int len = array.length;
        for (int i = 0; i < len/2; i++) {
            final T temp = array[i];
            array[i] = array[len-(i+1)];
            array[len-(i+1)] = temp;
        }
        return array;
    }

A implementation using generics for arrays of non primitive types.

    //Reverse and get new Array -preferred
    public static final <T> T[] reverse(final T[] array) {
        final int len = array.length;
        final T[] reverse = (T[]) Array.newInstance(array.getClass().getComponentType(), len);
        for (int i = 0; i < len; i++) {
            reverse[i] = array[len-(i+1)];
        }
        return reverse;
    }
    
    //Reverse existing array - don't have to return it
    public static final <T> T[] reverseExisting(final T[] array) {
        final int len = array.length;
        for (int i = 0; i < len/2; i++) {
            final T temp = array[i];
            array[i] = array[len-(i+1)];
            array[len-(i+1)] = temp;
        }
        return array;
    }
岁月染过的梦 2024-08-25 19:11:59

下面是在您的机器上运行的完整程序。

public class ReverseArray {
    public static void main(String[] args) {
        int arr[] = new int[] { 10,20,30,50,70 };
        System.out.println("reversing an array:");
        for(int i = 0; i < arr.length / 2; i++){
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }   
    }
}

对于使用数组的矩阵程序 这将是一个很好的来源< /a>.浏览链接。

below is the complete program to run in your machine.

public class ReverseArray {
    public static void main(String[] args) {
        int arr[] = new int[] { 10,20,30,50,70 };
        System.out.println("reversing an array:");
        for(int i = 0; i < arr.length / 2; i++){
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }   
    }
}

For programs on matrix using arrays this will be the good source.Go through the link.

南巷近海 2024-08-25 19:11:59
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;
} 
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;
} 
情徒 2024-08-25 19:11:59

这是一个简单的实现,用于反转任何类型的数组,以及完全/部分支持。

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

这是相应的单元测试

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}

Here is a simple implementation, to reverse array of any type, plus full/partial support.

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

Here is the corresponding Unit Test

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}
疯狂的代价 2024-08-25 19:11:59

这是我想出的:

// solution 1 - boiler plated 
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];

int lastIdx = original.length -1;
int startIdx = 0;

for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
   reverse[startIdx] = original[endIdx];

System.out.printf("reverse form: %s", Arrays.toString(reverse));

// solution 2 - abstracted 
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);

Here is what I've come up with:

// solution 1 - boiler plated 
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];

int lastIdx = original.length -1;
int startIdx = 0;

for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
   reverse[startIdx] = original[endIdx];

System.out.printf("reverse form: %s", Arrays.toString(reverse));

// solution 2 - abstracted 
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);
岁月如刀 2024-08-25 19:11:59
static int[] reverseArray(int[] a) {
     int ret[] = new int[a.length];
     for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
         ret[i] = a[j];
     return ret;
}
static int[] reverseArray(int[] a) {
     int ret[] = new int[a.length];
     for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
         ret[i] = a[j];
     return ret;
}
又怨 2024-08-25 19:11:58

要反转 int 数组,请向上交换项目,直到到达中点,如下所示:

for(int i = 0; i < validData.length / 2; i++)
{
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

按照您执行此操作的方式,将每个元素交换两次,因此结果与初始列表相同。

To reverse an int array, you swap items up until you reach the midpoint, like this:

for(int i = 0; i < validData.length / 2; i++)
{
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

分分钟 2024-08-25 19:11:58

使用 Commons.Lang,您可以简单地使用

ArrayUtils.reverse(int[] array)

大多数时候,它更快、更安全当它们解决您的问题时,坚持使用已经过单元测试和用户测试的易于使用的库。

With Commons.Lang, you could simply use

ArrayUtils.reverse(int[] array)

Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.

梦忆晨望 2024-08-25 19:11:58
Collections.reverse(Arrays.asList(yourArray));

java.util.Collections.reverse() 可以反转 java.util.Listjava.util.Arrays.asList() 返回一个list 包装了您传递给它的特定数组,因此 yourArray 在调用 Collections.reverse() 后会反转。

成本只是创建一个列表对象,不需要额外的库。

塔里克及其评论者的答案中提出了类似的解决方案,但我认为这个答案会更简洁,更容易解析。

Collections.reverse(Arrays.asList(yourArray));

java.util.Collections.reverse() can reverse java.util.Lists and java.util.Arrays.asList() returns a list that wraps the the specific array you pass to it, therefore yourArray is reversed after the invocation of Collections.reverse().

The cost is just the creation of one List-object and no additional libraries are required.

A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.

你的背包 2024-08-25 19:11:58
public class ArrayHandle {
    public static Object[] reverse(Object[] arr) {
        List<Object> list = Arrays.asList(arr);
        Collections.reverse(list);
        return list.toArray();
    }
}
public class ArrayHandle {
    public static Object[] reverse(Object[] arr) {
        List<Object> list = Arrays.asList(arr);
        Collections.reverse(list);
        return list.toArray();
    }
}
み青杉依旧 2024-08-25 19:11:58

我认为,如果您声明显式变量来跟踪在循环的每次迭代中交换的索引,那么遵循算法的逻辑会更容易一些。

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--;
    }
}

I think it's a little bit easier to follow the logic of the algorithm if you declare explicit variables to keep track of the indices that you're swapping at each iteration of the loop.

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;
    }
}

I also think it's more readable to do this in a while loop.

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--;
    }
}
沫雨熙 2024-08-25 19:11:58

使用流来反转

这里已经有很多答案,主要集中在就地修改数组。但为了完整起见,这里有另一种方法,使用 Java 流来保留原始数组并创建一个新的反转数组:

int[] a = {8, 6, 7, 5, 3, 0, 9};
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();

Use a stream to reverse

There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array:

int[] a = {8, 6, 7, 5, 3, 0, 9};
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
平定天下 2024-08-25 19:11:58

对于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]

In case of Java 8 we can also use IntStream to reverse the array of integers as:

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]
如歌彻婉言 2024-08-25 19:11:58

Guava

使用 Google Guava 库:

Collections.reverse(Ints.asList(array));

Guava

Using the Google Guava library:

Collections.reverse(Ints.asList(array));
慕烟庭风 2024-08-25 19:11:58
for(int i=validData.length-1; i>=0; i--){
  System.out.println(validData[i]);
 }
for(int i=validData.length-1; i>=0; i--){
  System.out.println(validData[i]);
 }
極樂鬼 2024-08-25 19:11:58

简单的for循环!

for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
    int aux = array[start];
    array[start]=array[end];
    array[end]=aux;
}

Simple for loop!

for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
    int aux = array[start];
    array[start]=array[end];
    array[end]=aux;
}
阳光下的泡沫是彩色的 2024-08-25 19:11:58

如果使用更原始的数据(即字符、字节、整数等),那么您可以执行一些有趣的异或运算。

public static void reverseArray4(int[] array) {
    int len = array.length;
    for (int i = 0; i < len/2; i++) {
        array[i] = array[i] ^ array[len - i  - 1];
        array[len - i  - 1] = array[i] ^ array[len - i  - 1];
        array[i] = array[i] ^ array[len - i  - 1];
    }
}

If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.

public static void reverseArray4(int[] array) {
    int len = array.length;
    for (int i = 0; i < len/2; i++) {
        array[i] = array[i] ^ array[len - i  - 1];
        array[len - i  - 1] = array[i] ^ array[len - i  - 1];
        array[i] = array[i] ^ array[len - i  - 1];
    }
}
暖阳 2024-08-25 19:11:58

这会帮助你

int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
    int temp = a[k];
    a[k] = a[a.length-(1+k)];
    a[a.length-(1+k)] = temp;
}

This will help you

int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
    int temp = a[k];
    a[k] = a[a.length-(1+k)];
    a[a.length-(1+k)] = temp;
}
¢好甜 2024-08-25 19:11:58

这就是我个人解决这个问题的方法。创建参数化方法背后的原因是允许对任何数组进行排序......而不仅仅是整数。

我希望你能从中有所收获。

@Test
public void reverseTest(){
   Integer[] ints = { 1, 2, 3, 4 };
   Integer[] reversedInts = reverse(ints);

   assert ints[0].equals(reversedInts[3]);
   assert ints[1].equals(reversedInts[2]);
   assert ints[2].equals(reversedInts[1]);
   assert ints[3].equals(reversedInts[0]);

   reverseInPlace(reversedInts);
   assert ints[0].equals(reversedInts[0]);
}

@SuppressWarnings("unchecked")
private static <T> T[] reverse(T[] array) {
    if (array == null) {
        return (T[]) new ArrayList<T>().toArray();
    }
    List<T> copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
    Collections.reverse(copyOfArray);
    return copyOfArray.toArray(array);
}

private static <T> T[] reverseInPlace(T[] array) {
    if(array == null) {
        // didn't want two unchecked suppressions
        return reverse(array);
    }

    Collections.reverse(Arrays.asList(array));
    return array;
}

This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.

I hope you glean something from it.

@Test
public void reverseTest(){
   Integer[] ints = { 1, 2, 3, 4 };
   Integer[] reversedInts = reverse(ints);

   assert ints[0].equals(reversedInts[3]);
   assert ints[1].equals(reversedInts[2]);
   assert ints[2].equals(reversedInts[1]);
   assert ints[3].equals(reversedInts[0]);

   reverseInPlace(reversedInts);
   assert ints[0].equals(reversedInts[0]);
}

@SuppressWarnings("unchecked")
private static <T> T[] reverse(T[] array) {
    if (array == null) {
        return (T[]) new ArrayList<T>().toArray();
    }
    List<T> copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
    Collections.reverse(copyOfArray);
    return copyOfArray.toArray(array);
}

private static <T> T[] reverseInPlace(T[] array) {
    if(array == null) {
        // didn't want two unchecked suppressions
        return reverse(array);
    }

    Collections.reverse(Arrays.asList(array));
    return array;
}
浅浅 2024-08-25 19:11:58

有两种方法可以解决该问题:

1.在空间中反转数组。

步骤 1. 交换起始索引和结束索引处的元素。

步骤 2. 增加起始索引并减少结束索引。

步骤3. 迭代步骤1和步骤2,直到起始索引<1。 end index

为此,时间复杂度为 O(n),空间复杂度为 O(1)

在空间中反转数组的示例代码如下:

public static int[] reverseAnArrayInSpace(int[] array) {
    int startIndex = 0;
    int endIndex = array.length - 1;
    while(startIndex < endIndex) {
        int temp = array[endIndex];
        array[endIndex] = array[startIndex];
        array[startIndex] = temp;
        startIndex++;
        endIndex--;
    }
    return array;
}

2.使用辅助数组反转数组。

步骤 1. 创建一个大小等于给定数组的新数组。

步骤 2. 从起始索引开始向新数组中插入元素
给定数组从结束索引开始。

为此,时间复杂度为 O(n),空间复杂度为 O(n)

使用辅助数组反转数组的示例代码如下:

public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
    int[] reversedArray = new int[array.length];
    for(int index = 0; index < array.length; index++) {
        reversedArray[index] = array[array.length - index -1]; 
    }
    return reversedArray;
}

此外,我们可以使用 Java 中的 Collections API 来执行此操作.

Collections API 在内部使用相同的反向空间方法。

使用 Collections API 的示例代码如下:

public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
    List<Integer> arrayList = Arrays.asList(array);
    Collections.reverse(arrayList);
    return arrayList.toArray(array);
}

There are two ways to have a solution for the problem:

1. Reverse an array in space.

Step 1. Swap the elements at the start and the end index.

Step 2. Increment the start index decrement the end index.

Step 3. Iterate Step 1 and Step 2 till start index < end index

For this, the time complexity will be O(n) and the space complexity will be O(1)

Sample code for reversing an array in space is like:

public static int[] reverseAnArrayInSpace(int[] array) {
    int startIndex = 0;
    int endIndex = array.length - 1;
    while(startIndex < endIndex) {
        int temp = array[endIndex];
        array[endIndex] = array[startIndex];
        array[startIndex] = temp;
        startIndex++;
        endIndex--;
    }
    return array;
}

2. Reverse an array using an auxiliary array.

Step 1. Create a new array of size equal to the given array.

Step 2. Insert elements to the new array starting from the start index, from the
given array starting from end index.

For this, the time complexity will be O(n) and the space complexity will be O(n)

Sample code for reversing an array with auxiliary array is like:

public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
    int[] reversedArray = new int[array.length];
    for(int index = 0; index < array.length; index++) {
        reversedArray[index] = array[array.length - index -1]; 
    }
    return reversedArray;
}

Also, we can use the Collections API from Java to do this.

The Collections API internally uses the same reverse in space approach.

Sample code for using the Collections API is like:

public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
    List<Integer> arrayList = Arrays.asList(array);
    Collections.reverse(arrayList);
    return arrayList.toArray(array);
}
后eg是否自 2024-08-25 19:11:58

您的程序仅适用于 length = 0, 1
您可以尝试:

int i = 0, j = validData.length-1 ; 
while(i < j)
{
     swap(validData, i++, j--);  // code for swap not shown, but easy enough
}

Your program will work for only length = 0, 1.
You can try :

int i = 0, j = validData.length-1 ; 
while(i < j)
{
     swap(validData, i++, j--);  // code for swap not shown, but easy enough
}
狼亦尘 2024-08-25 19:11:58

上面有一些很好的答案,但这就是我的做法:

public static int[] test(int[] arr) {

    int[] output = arr.clone();
    for (int i = arr.length - 1; i > -1; i--) {
        output[i] = arr[arr.length - i - 1];
    }
    return output;
}

There are some great answers above, but this is how I did it:

public static int[] test(int[] arr) {

    int[] output = arr.clone();
    for (int i = arr.length - 1; i > -1; i--) {
        output[i] = arr[arr.length - i - 1];
    }
    return output;
}
浊酒尽余欢 2024-08-25 19:11:58

简单地向后迭代数组是最有效的。

我不确定 Aaron 的解决方案是否会执行此 vi 此调用 Collections.reverse(list); 有谁知道吗?

It is most efficient to simply iterate the array backwards.

I'm not sure if Aaron's solution does this vi this call Collections.reverse(list); Does anyone know?

回首观望 2024-08-25 19:11:58
public void getDSCSort(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;
        }
    }
public void getDSCSort(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;
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文