在不创建新数组的情况下反转字符数组

时间:2009-11-08 12:56:12

标签: arrays algorithm reverse

如何在适当的位置反转数组(不创建新数组)?

13 个答案:

答案 0 :(得分:9)

家庭作业仅指我的伪代码,你通过不指定你想要的语言而相对容易: - )

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

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
  • temporary variable

我倾向于为更简单的算法做到这一点。更难的我插入调试语句,以便计算机可以为我做那些笨拙的工作。从一张纸开始:

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

然后逐个执行这些步骤,检查和/或更改每个列。这将使您了解它的工作方式远比给出一些代码更好。

答案 1 :(得分:9)

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

答案 2 :(得分:2)

在不使用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数组,则必须将public static void reverseArray(String[] array)更改为public static void reverseArray(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]

答案 3 :(得分:1)

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

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

等等。

答案 4 :(得分:1)

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

答案 5 :(得分:0)

不要在内存中反转数组,只需向后迭代它!

答案 6 :(得分:0)

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

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

谢谢,

答案 7 :(得分:0)

这是一个完整的程序,只需复制粘贴并在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

答案 8 :(得分:0)

在不创建新数组的情况下反转字符数组

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

答案 9 :(得分:0)

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

答案 10 :(得分:0)

  • 使用临时变量临时保存变量
  • 使用两个索引指针,一个来自第一个索引,最后一个来自数组长度
  • 迭代数组直到数组元素的中间
  • 下面是我创建的用于执行相同功能的功能
  • 它适用于偶数和奇数大小
  • 输入数组1 4 3 2
  • 期望2 3 4 1

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

constexpr

答案 11 :(得分:0)

library(shiny)

# USER INTERFACE
ui <- fluidPage(
  # Give the page a title
  titlePanel("Kalkulator CCT"),
  helpText("Aplikasi ini menghitung creatinine clearance berdasarkan rumus CKD-EPI dan ditambahkan dengan penyesuaian dosis antibiotik "),
  # left input 
  sidebarPanel(
    
    
    radioButtons(inputId = "sex", label = "Sex", choices = c("Male", "Female"), inline = TRUE),
    
    
    numericInput(inputId = "age", label = "Age (years)", value = 18, min = 0, max = 100, width=validateCssUnit("50%")),
    uiOutput("age"),                         
    numericInput(inputId = "cre", label = "Serum creatinine (mg/dL", value = 0.89, min = 0, max = 10, width=validateCssUnit("50%")),
    uiOutput("cre"),
    radioButtons("ab", "Type of antibiotics:",
                       c("Meropenem",
                         "Levofloxacin"
                       )),
    helpText("Choose the antibiotics")
    
  ),
  # right outputs
  mainPanel(br(),
            # h3("Results"),
            br(),
            dataTableOutput("results"), width=6 )
)





# SERVER function

server <- function(input, output, session) {
  
  
  # Evaluate Design Effect for selected options, and output table with values
  results.data.table <- reactive({
    
    CCT <- cct(input$sex, input$cre, input$age)
    finalresult<-data.frame(Result = "CCT", Value = CCT, Antibiotics = ab_text(input$ab, CCT))
    
  })
  
  
  # Output data table results without any data table options (page no., row number, etc..)
  output$results <- renderDataTable({results.data.table()}, options = list(lengthChange= F, paging = F, searching = F, ordering= F, info=F))
  
  
}

shinyApp(ui = ui, server = server)

答案 12 :(得分:-1)

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