反转字符数组而不创建新数组

发布于 2024-08-10 16:14:25 字数 25 浏览 2 评论 0原文

如何就地反转数组(无需创建新数组)?

How can I reverse an array in place (without creating a new array)?

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

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

发布评论

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

评论(13

内心旳酸楚 2024-08-17 16:14:26

反转字符数组而不创建新数组

public static void main(String[] args) {
    char[] a = {'1', '2', '3','4'};
    char temp = ' ';
    for (int i = 0; i < a.length / 2; i++) {
        temp = a[i];
        a[i] = a[a.length - 1 - i];
        a[a.length - 1 - i] = temp;
    }
    System.out.println(a);
}

reversing an array of characters without creating a new array

public static void main(String[] args) {
    char[] a = {'1', '2', '3','4'};
    char temp = ' ';
    for (int i = 0; i < a.length / 2; i++) {
        temp = a[i];
        a[i] = a[a.length - 1 - i];
        a[a.length - 1 - i] = temp;
    }
    System.out.println(a);
}
等待圉鍢 2024-08-17 16:14:26
Array.prototype.reverse = function() {
  for(var i = 0, j = this.length-1; i < j; i++, j--) {
    var tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
  }
  return this;
};
Array.prototype.reverse = function() {
  for(var i = 0, j = this.length-1; i < j; i++, j--) {
    var tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
  }
  return this;
};
静待花开 2024-08-17 16:14:26

不必费心在内存中反转数组,只需向后迭代即可!

Dont bother reversing the array in memory, just iterate over it backwards!

っ〆星空下的拥抱 2024-08-17 16:14:26

这是在不使用临时变量或其他数组的情况下反转数组元素的解决方案。这仅适用于 Java 8 及以上版本。

void invertUsingStreams(Object[] arr2) {
    IntStream.rangeClosed(1,arr2.length)
       .mapToObj(i -> arr2[arr2.length-i])
       .forEach(System.out::println);
}

谢谢,

Here is the solution to reverse an array elements without using temp variable or another array. This will work only Java 8 and above version.

void invertUsingStreams(Object[] arr2) {
    IntStream.rangeClosed(1,arr2.length)
       .mapToObj(i -> arr2[arr2.length-i])
       .forEach(System.out::println);
}

Thanks,

网名女生简单气质 2024-08-17 16:14:26

这是一个完整的程序,只需复制粘贴并在 IDE 中运行它:

public class ReverseArrayWithoutAnotherArray {

public static void main(String[] args) {

    int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    int middle = array.length / 2;

    int temp;
    int j = array.length -1;

    for(int a : array){
        System.out.println(" before reverse :: " + a);
    }
    for (int i = 0 ; i < middle; i++, j--) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    for(int a : array){
        System.out.println(" after reverse :: " + a);
    }
}
}

输出:

 before reverse :: 1
 before reverse :: 2
 before reverse :: 3
 before reverse :: 4
 before reverse :: 5
 before reverse :: 6
 before reverse :: 7
 before reverse :: 8
 before reverse :: 9
 before reverse :: 10
 after reverse :: 10
 after reverse :: 9
 after reverse :: 8
 after reverse :: 7
 after reverse :: 6
 after reverse :: 5
 after reverse :: 4
 after reverse :: 3
 after reverse :: 2
 after reverse :: 1

Here is a complete program, just copy paste and run it in your IDE :

public class ReverseArrayWithoutAnotherArray {

public static void main(String[] args) {

    int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    int middle = array.length / 2;

    int temp;
    int j = array.length -1;

    for(int a : array){
        System.out.println(" before reverse :: " + a);
    }
    for (int i = 0 ; i < middle; i++, j--) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    for(int a : array){
        System.out.println(" after reverse :: " + a);
    }
}
}

output :

 before reverse :: 1
 before reverse :: 2
 before reverse :: 3
 before reverse :: 4
 before reverse :: 5
 before reverse :: 6
 before reverse :: 7
 before reverse :: 8
 before reverse :: 9
 before reverse :: 10
 after reverse :: 10
 after reverse :: 9
 after reverse :: 8
 after reverse :: 7
 after reverse :: 6
 after reverse :: 5
 after reverse :: 4
 after reverse :: 3
 after reverse :: 2
 after reverse :: 1
空‖城人不在 2024-08-17 16:14:26
  • 使用临时变量临时保存变量
  • 使用两个索引指针,一个是从第一个索引开始,最后一个是从数组长度
  • 迭代数组直到数组元素的中间
  • 下面是我创建的函数,
  • 它对偶数和奇数都适用大小
  • 输入数组 1 4 3 2
  • 预期输出 2 3 4 1

static int[] reverseArray(int[] a) {

    int j=a.length-1; // last index pointer

    int middle = a.length/2; // end condition

    for (int i=0;i<middle;i++){
        int temp=a[i];
        a[i]=a[j];
        a[j]=temp;
        j--;
    }

    return a;

}
  • Use temp variables to temporary hold the variables
  • use two index pointer, one is from first index and last from array length
  • iterate the array till the middle of the array elements
  • Below is the function i created to do the same
  • it works for both even and odd size
  • Input Array 1 4 3 2
  • Expected Out 2 3 4 1

static int[] reverseArray(int[] a) {

    int j=a.length-1; // last index pointer

    int middle = a.length/2; // end condition

    for (int i=0;i<middle;i++){
        int temp=a[i];
        a[i]=a[j];
        a[j]=temp;
        j--;
    }

    return a;

}
别忘他 2024-08-17 16:14:26
var arr = [1,2,3,4,5,6]
for(let i=arr.length-2;i>=0;i--){
   arr.push(arr.splice(i,1)[0])
}
console.log(arr) // [6,5,4,3,2,1]

var arr2 = [1,2,3,4,5,6]
for(let i=0,j=arr2.length-1;i<arr2.length/2;i++){
   let temp = arr2[i];
   arr2[i] = arr2[j-i];
   arr2[j-i] = temp
}
console.log(arr2) // [6,5,4,3,2,1]

var arr = [1,2,3,4,5,6]
for(let i=arr.length-2;i>=0;i--){
   arr.push(arr.splice(i,1)[0])
}
console.log(arr) // [6,5,4,3,2,1]

var arr2 = [1,2,3,4,5,6]
for(let i=0,j=arr2.length-1;i<arr2.length/2;i++){
   let temp = arr2[i];
   arr2[i] = arr2[j-i];
   arr2[j-i] = temp
}
console.log(arr2) // [6,5,4,3,2,1]

软糯酥胸 2024-08-17 16:14:26
import java.util.Scanner;
import java.util.Arrays;

public class reversearray {
    private static Scanner scanner=new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("enter the count value ");
        int n=scanner.nextInt();
        int[] value=new int[n];
        System.out.println("enter the elements of an array");
        for(int i=0;i<n;i++)
        {
            value[i]=scanner.nextInt();
        }
        reverse(value);

    }
    public static void reverse(int[] array) {
        int n = array.length - 1;
        int temp = 0;
        int count=0;
        boolean swapped = true;
        int mid = n / 2;

        for (int i = 0; i < mid; i++) {
            temp = array[i];
            array[i] = array[n - i];
            array[n - i] = temp;
            count++;
        }
        if(count==(n-mid))
        {
            array[mid]=array[mid];
        }
        else
        {
            temp=array[mid];
            array[mid]=array[mid+1];
            array[mid+1]=temp;
        }

        System.out.println("the reveresed array elements are: " + Arrays.toString(array));
    }
}
import java.util.Scanner;
import java.util.Arrays;

public class reversearray {
    private static Scanner scanner=new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("enter the count value ");
        int n=scanner.nextInt();
        int[] value=new int[n];
        System.out.println("enter the elements of an array");
        for(int i=0;i<n;i++)
        {
            value[i]=scanner.nextInt();
        }
        reverse(value);

    }
    public static void reverse(int[] array) {
        int n = array.length - 1;
        int temp = 0;
        int count=0;
        boolean swapped = true;
        int mid = n / 2;

        for (int i = 0; i < mid; i++) {
            temp = array[i];
            array[i] = array[n - i];
            array[n - i] = temp;
            count++;
        }
        if(count==(n-mid))
        {
            array[mid]=array[mid];
        }
        else
        {
            temp=array[mid];
            array[mid]=array[mid+1];
            array[mid+1]=temp;
        }

        System.out.println("the reveresed array elements are: " + Arrays.toString(array));
    }
}
思念满溢 2024-08-17 16:14:25
public static int[] reverseArrayWithoutTempArray(int[] array) {
    int i = 0, j = array.length - 1;
    for (i = 0; i < array.length / 2; i++, j--) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
public static int[] reverseArrayWithoutTempArray(int[] array) {
    int i = 0, j = array.length - 1;
    for (i = 0; i < array.length / 2; i++, j--) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
寒冷纷飞旳雪 2024-08-17 16:14:25

家庭作业意味着仅由我提供的伪代码,通过不指定您想要的语言,您已经使伪代码变得相对容易:-)

将其转换为您选择的语言:

Set i1 to index of first element in array
Set i2 to index of last element in array
while i1 < i2:
    Set temporary variable to element number i1
    Set element number i1 to element number i2
    Set element number i2 to temporary value
    Add 1 to i1
    Subtract 1 from i2

理想的做法是在您的头脑中实际运行该算法,使用一张纸来跟踪变量:

  • 数组中的每个元素。
  • i1i2
  • 临时变量

我倾向于为更简单的算法这样做。对于更难的任务,我会插入调试语句,以便计算机可以为我完成这项繁重的工作。因此,从一张纸开始:

i1 | i2 | tempvar | el[0] | el[1] | el[2] | el[3] | el[4] | el[5]
---+----+---------+-------+-------+-------+-------+-------+------
                      H       e       l       l       o       !

然后逐个执行步骤,检查和/或更改每一列。这将使您比仅仅给出一些代码更好地理解它是如何工作的。

Homework means pseudo-code only from me, which you've made relatively easy by not specifying what language you want anyway :-)

Turn this into your language of choice:

Set i1 to index of first element in array
Set i2 to index of last element in array
while i1 < i2:
    Set temporary variable to element number i1
    Set element number i1 to element number i2
    Set element number i2 to temporary value
    Add 1 to i1
    Subtract 1 from i2

An ideal thing to do is to actually run that algorithm in your head, using a piece of paper to keep track of variables:

  • each the elements in the array.
  • i1 and i2.
  • temporary variable.

I tend to do that for simpler algorithms. Harder ones I insert debug statement into so that the computer can do that grunt work for me. Start with a piece of paper thus:

i1 | i2 | tempvar | el[0] | el[1] | el[2] | el[3] | el[4] | el[5]
---+----+---------+-------+-------+-------+-------+-------+------
                      H       e       l       l       o       !

and just run through the steps one by one, checking and/or changing each column as you go. That will result in you understanding how it works far better than just being given some code.

天煞孤星 2024-08-17 16:14:25

使用 java 反转字符数组而不创建新数组。

import java.util.*;


//Reverse string array
public static void reverseArray(String[] array){

    int middle = array.length / 2;

    String temp;
    int j = array.length -1;

    for (int i = 0 ; i < middle; i++) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
        j--;
    }

    System.out.println(Arrays.toString(array));
}

如果你想反转int array,你必须将public static void reviveArray(String[] array)更改为public static void reviveArray(int[] array)String temp 作为 int temp

示例:

public static void main (String[] args) throws java.lang.Exception{
      String[] array = {"Smith", "Peter", "Michel", "John"};
      reverseArray(array);
}

输出:

[John, Michel, Peter, Smith]

Reverse an array of characters without creating a new array using java.

import java.util.*;


//Reverse string array
public static void reverseArray(String[] array){

    int middle = array.length / 2;

    String temp;
    int j = array.length -1;

    for (int i = 0 ; i < middle; i++) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
        j--;
    }

    System.out.println(Arrays.toString(array));
}

If you want to reverse int array, you have to change public static void reverseArray(String[] array) as public static void reverseArray(int[] array) and String temp as int temp.

Example:

public static void main (String[] args) throws java.lang.Exception{
      String[] array = {"Smith", "Peter", "Michel", "John"};
      reverseArray(array);
}

Output :

[John, Michel, Peter, Smith]
烏雲後面有陽光 2024-08-17 16:14:25

使用单个变量作为临时缓冲区,不断交换两端。在伪代码中:

temp = a[0]
a[0] = a[size - 1]
a[size - 1] = temp

等等。

Swap the ends constantly, using a single variable as a temporary buffer. In pseudo-code:

temp = a[0]
a[0] = a[size - 1]
a[size - 1] = temp

and so on.

陈年往事 2024-08-17 16:14:25
public static void main(String args[]){
            int j=arr.length;       
for(int i=0;i<arr.length/2;i++){
            int temp=arr[i];
            arr[i]=arr[j-1-i];
            arr[j-1-i]=temp;}
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
public static void main(String args[]){
            int j=arr.length;       
for(int i=0;i<arr.length/2;i++){
            int temp=arr[i];
            arr[i]=arr[j-1-i];
            arr[j-1-i]=temp;}
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文