Java,移动数组中的元素

发布于 2024-12-13 01:50:51 字数 340 浏览 4 评论 0原文

我有一个 Java 对象数组,我试图将一个元素拉到顶部,并将其余元素向下移动一个。

假设我有一个大小为 10 的数组,并且我正在尝试提取第五个元素。第五个元素进入位置 0,并且从 0 到 5 的所有元素都将向下移动 1。

该算法无法正确移动元素:

Object temp = pool[position];

for (int i = 0; i < position; i++) {                
    array[i+1] = array[i];
}
array[0] = temp;

我该如何正确地做到这一点?

I have an array of objects in Java, and I am trying to pull one element to the top and shift the rest down by one.

Assume I have an array of size 10, and I am trying to pull the fifth element. The fifth element goes into position 0 and all elements from 0 to 5 will be shifted down by one.

This algorithm does not properly shift the elements:

Object temp = pool[position];

for (int i = 0; i < position; i++) {                
    array[i+1] = array[i];
}
array[0] = temp;

How do I do it correctly?

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

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

发布评论

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

评论(18

成熟稳重的好男人 2024-12-20 01:50:52

编写一个Java程序,创建一个包含20个整数的数组,然后实现将数组右移两个元素的过程。

public class NewClass3 {
    
     public static void main (String args[]){
     
     int a [] = {1,2,};
    
     int temp ;
     
     for(int i = 0; i<a.length -1; i++){
      
         temp = a[i];
         a[i] = a[i+1];
         a[i+1] = temp;
     
     }
     
     for(int p : a)
     System.out.print(p);
     }
    
}

Write a Java program to create an array of 20 integers, and then implement the process of shifting the array to right for two elements.

public class NewClass3 {
    
     public static void main (String args[]){
     
     int a [] = {1,2,};
    
     int temp ;
     
     for(int i = 0; i<a.length -1; i++){
      
         temp = a[i];
         a[i] = a[i+1];
         a[i+1] = temp;
     
     }
     
     for(int p : a)
     System.out.print(p);
     }
    
}
我不在是我 2024-12-20 01:50:51

从逻辑上讲,它不起作用,您应该反转循环:

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

或者您可以使用

System.arraycopy(array, 0, array, 1, position);

Logically it does not work and you should reverse your loop:

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

Alternatively you can use

System.arraycopy(array, 0, array, 1, position);
撕心裂肺的伤痛 2024-12-20 01:50:51

假设您的数组是 {10,20,30,40,50,60,70,80,90,100}

您的循环执行的操作是:

迭代 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

迭代 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

你应该做的是

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

Assuming your array is {10,20,30,40,50,60,70,80,90,100}

What your loop does is:

Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

What you should be doing is

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;
溇涏 2024-12-20 01:50:51

您只需使用 Collections.rotate(List list, int distance)

使用 Arrays.asList(array) 转换为 List

更多信息位于:https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)

You can just use Collections.rotate(List<?> list, int distance)

Use Arrays.asList(array) to convert to List

more info at: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)

只等公子 2024-12-20 01:50:51

只是为了完整性:自 Java 8 以来的流解决方案。

final String[] shiftedArray = Arrays.stream(array)
        .skip(1)
        .toArray(String[]::new);

我想我在您的情况下坚持使用 System.arraycopy() 。但最好的长期解决方案可能是将所有内容都转换为不可变集合(GuavaVavr),只要这些集合是短暂的。

Just for completeness: Stream solution since Java 8.

final String[] shiftedArray = Arrays.stream(array)
        .skip(1)
        .toArray(String[]::new);

I think I sticked with the System.arraycopy() in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.

亽野灬性zι浪 2024-12-20 01:50:51

您可以使用这样的模块使此功能更加通用,而不是移动一个位置。

int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;

for(int i=0; i<original.length;i++)
     reordered[i] = original[(shift+i)%original.length];

Instead of shifting by one position you can make this function more general using module like this.

int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;

for(int i=0; i<original.length;i++)
     reordered[i] = original[(shift+i)%original.length];
孤单情人 2024-12-20 01:50:51

正如您所发现的,以这种方式操作数组很容易出错。更好的选择可能是使用 LinkedList在你的情况下。对于链表和所有 Java 集合,数组管理是在内部处理的,因此您不必担心元素的移动。使用 LinkedList,您只需调用 remove ,然后调用 addLast 即可完成。

Manipulating arrays in this way is error prone, as you've discovered. A better option may be to use a LinkedList in your situation. With a linked list, and all Java collections, array management is handled internally so you don't have to worry about moving elements around. With a LinkedList you just call remove and then addLast and the you're done.

極樂鬼 2024-12-20 01:50:51

试试这个:

Object temp = pool[position];

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

在这里查看它的工作原理:http://www.ideone.com/5JfAg

Try this:

Object temp = pool[position];

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

Look here to see it working: http://www.ideone.com/5JfAg

他是夢罘是命 2024-12-20 01:50:51

使用数组复制
k 次移位 k=1 或 k=3 等

public void rotate(int[] nums, int k) {
            //  Step 1
            // k > array length then we dont need to shift k times because when we shift
            // array length times then the array will go back to intial position.
            // so we can just do only k%array length times.
            // change k = k% array.length;
    
            if (k > nums.length) {
                k = k % nums.length;
            }
            
            //   Step 2;
            // initialize temporary array with same length of input array.
            // copy items from input array starting from array length -k as source till
            // array end and place in new array starting from index 0;
            int[] tempArray = new int[nums.length];
    
            System.arraycopy(nums, nums.length - k, tempArray, 0, k);
            
            //   step3:
            // loop and copy all the remaining elements till array length -k index and copy
            // in result array starting from position k
            for (int i = 0; i < nums.length - k; i++) {
                tempArray[k + i] = nums[i];
            }
            
            // step 4 copy temp array to input array since our goal is to change input
            // array.
    
            System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
    
        }

代码的通用解决方案

 public void rotate(int[] nums, int k) {
                if (k > nums.length) {
                    k = k % nums.length;
                }
                int[] tempArray = new int[nums.length];
                System.arraycopy(nums, nums.length - k, tempArray, 0, k);
                for (int i = 0; i < nums.length - k; i++) {
                    tempArray[k + i] = nums[i];
                }
                System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
            }

Using array Copy
Generic solution for k times shift k=1 or k=3 etc

public void rotate(int[] nums, int k) {
            //  Step 1
            // k > array length then we dont need to shift k times because when we shift
            // array length times then the array will go back to intial position.
            // so we can just do only k%array length times.
            // change k = k% array.length;
    
            if (k > nums.length) {
                k = k % nums.length;
            }
            
            //   Step 2;
            // initialize temporary array with same length of input array.
            // copy items from input array starting from array length -k as source till
            // array end and place in new array starting from index 0;
            int[] tempArray = new int[nums.length];
    
            System.arraycopy(nums, nums.length - k, tempArray, 0, k);
            
            //   step3:
            // loop and copy all the remaining elements till array length -k index and copy
            // in result array starting from position k
            for (int i = 0; i < nums.length - k; i++) {
                tempArray[k + i] = nums[i];
            }
            
            // step 4 copy temp array to input array since our goal is to change input
            // array.
    
            System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
    
        }

code

 public void rotate(int[] nums, int k) {
                if (k > nums.length) {
                    k = k % nums.length;
                }
                int[] tempArray = new int[nums.length];
                System.arraycopy(nums, nums.length - k, tempArray, 0, k);
                for (int i = 0; i < nums.length - k; i++) {
                    tempArray[k + i] = nums[i];
                }
                System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
            }
赢得她心 2024-12-20 01:50:51

在循环的第一次迭代中,您将覆盖 array[1] 中的值。您应该以相反的顺序查看索引。

In the first iteration of your loop, you overwrite the value in array[1]. You should go through the indicies in the reverse order.

呢古 2024-12-20 01:50:51
static void pushZerosToEnd(int arr[])
    {   int n = arr.length;
        int count = 0;  // Count of non-zero elements
        // Traverse the array. If element encountered is non-zero, then
        // replace the element at index 'count' with this element
        for (int i = 0; i < n; i++){
            if (arr[i] != 0)`enter code here`
               // arr[count++] = arr[i]; // here count is incremented
                swapNumbers(arr,count++,i);
        }
        for (int j = 0; j < n; j++){
            System.out.print(arr[j]+",");
        }
     }

    public static void swapNumbers(int [] arr, int pos1, int pos2){
        int temp  = arr[pos2];
        arr[pos2] = arr[pos1];
        arr[pos1] = temp;
    }
static void pushZerosToEnd(int arr[])
    {   int n = arr.length;
        int count = 0;  // Count of non-zero elements
        // Traverse the array. If element encountered is non-zero, then
        // replace the element at index 'count' with this element
        for (int i = 0; i < n; i++){
            if (arr[i] != 0)`enter code here`
               // arr[count++] = arr[i]; // here count is incremented
                swapNumbers(arr,count++,i);
        }
        for (int j = 0; j < n; j++){
            System.out.print(arr[j]+",");
        }
     }

    public static void swapNumbers(int [] arr, int pos1, int pos2){
        int temp  = arr[pos2];
        arr[pos2] = arr[pos1];
        arr[pos1] = temp;
    }
在巴黎塔顶看东京樱花 2024-12-20 01:50:51

如果您将数组数据作为 Java 列表,则还有另一种变体

    listOfStuff.add( 
            0, 
            listOfStuff.remove(listOfStuff.size() - 1) );

只是分享我为此遇到的另一个选项,但我认为答案来自 @ Murat Mustafin 是列出清单的最佳方式

Another variation if you have the array data as a Java-List

    listOfStuff.add( 
            0, 
            listOfStuff.remove(listOfStuff.size() - 1) );

Just sharing another option I ran across for this, but I think the answer from @Murat Mustafin is the way to go with a list

帅冕 2024-12-20 01:50:51
public class Test1 {

    public static void main(String[] args) {

        int[] x = { 1, 2, 3, 4, 5, 6 };
        Test1 test = new Test1();
        x = test.shiftArray(x, 2);
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + " ");
        }
    }

    public int[] pushFirstElementToLast(int[] x, int position) {
        int temp = x[0];
        for (int i = 0; i < x.length - 1; i++) {
            x[i] = x[i + 1];
        }
        x[x.length - 1] = temp;
        return x;
    }

    public int[] shiftArray(int[] x, int position) {
        for (int i = position - 1; i >= 0; i--) {
            x = pushFirstElementToLast(x, position);
        }
        return x;
    }
}
public class Test1 {

    public static void main(String[] args) {

        int[] x = { 1, 2, 3, 4, 5, 6 };
        Test1 test = new Test1();
        x = test.shiftArray(x, 2);
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + " ");
        }
    }

    public int[] pushFirstElementToLast(int[] x, int position) {
        int temp = x[0];
        for (int i = 0; i < x.length - 1; i++) {
            x[i] = x[i + 1];
        }
        x[x.length - 1] = temp;
        return x;
    }

    public int[] shiftArray(int[] x, int position) {
        for (int i = position - 1; i >= 0; i--) {
            x = pushFirstElementToLast(x, position);
        }
        return x;
    }
}
迷途知返 2024-12-20 01:50:51

对大小为 n 的数组进行左旋转操作会将数组的每个元素单位向左移动,检查一下!!!!!!!

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

    public static void main(String[] args) {
        String[] nd = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nd[0]);  //no. of elements in the array

        int d = Integer.parseInt(nd[1]);  //number of left rotations

        int[] a = new int[n]; 

      for(int i=0;i<n;i++){
          a[i]=scanner.nextInt();
      }

        Solution s= new Solution();     
//number of left rotations
        for(int j=0;j<d;j++){
              s.rotate(a,n);
        }
   //print the shifted array  
        for(int i:a){System.out.print(i+" ");}
    }

//shift each elements to the left by one 
   public static void rotate(int a[],int n){
            int  temp=a[0];
        for(int i=0;i<n;i++){
            if(i<n-1){a[i]=a[i+1];}
            else{a[i]=temp;}
      }}
}

A left rotation operation on an array of size n shifts each of the array's elements unit to the left, check this out!!!!!!

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

    public static void main(String[] args) {
        String[] nd = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nd[0]);  //no. of elements in the array

        int d = Integer.parseInt(nd[1]);  //number of left rotations

        int[] a = new int[n]; 

      for(int i=0;i<n;i++){
          a[i]=scanner.nextInt();
      }

        Solution s= new Solution();     
//number of left rotations
        for(int j=0;j<d;j++){
              s.rotate(a,n);
        }
   //print the shifted array  
        for(int i:a){System.out.print(i+" ");}
    }

//shift each elements to the left by one 
   public static void rotate(int a[],int n){
            int  temp=a[0];
        for(int i=0;i<n;i++){
            if(i<n-1){a[i]=a[i+1];}
            else{a[i]=temp;}
      }}
}
奈何桥上唱咆哮 2024-12-20 01:50:51

您可以使用以下代码进行移位而不是旋转:

    int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
            int n = arr.length;
            int d = 3;

用于将大小为 n 的数组向左移位 d 个元素的程序:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {4,5,6,7,8,9,10,11,12,10,11,12}

        public void shiftLeft(int []arr,int d,int n) {
            for(int i=0;i<n-d;i++) {
                arr[i] = arr[i+d];
            }
        }

用于将大小为 n 的数组移位的程序code> 向右的 d 元素:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {1,2,3,1,2,3,4,5,6,7,8,9}

        public void shiftRight(int []arr,int d,int n) {

            for(int i=n-1;i>=d;i--) {
                arr[i] = arr[i-d];
            }
        }

You can use the Below codes for shifting not rotating:

    int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
            int n = arr.length;
            int d = 3;

Programm for shifting array of size n by d elements towards left:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {4,5,6,7,8,9,10,11,12,10,11,12}

        public void shiftLeft(int []arr,int d,int n) {
            for(int i=0;i<n-d;i++) {
                arr[i] = arr[i+d];
            }
        }

Programm for shifting array of size n by d elements towards right:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {1,2,3,1,2,3,4,5,6,7,8,9}

        public void shiftRight(int []arr,int d,int n) {

            for(int i=n-1;i>=d;i--) {
                arr[i] = arr[i-d];
            }
        }
临走之时 2024-12-20 01:50:51
Left shift in java using java 8


import java.util.*;

class HelloWorld {
    public static void main(String[] args) {
        List<String> list= new ArrayList<>();
        list.add("akash");
        list.add("roopesh");
        list.add("rahul");
        list.add("anubhav");
        System.out.println(list);
        int a=2;
        if(a<=list.size()){
        List<String> resList= new ArrayList<>();
        for(int i=0; i<list.size();i++){
            if(i<list.size()-a){
            resList.add(list.get(i+a));
            }else if(i<list.size()){
                System.out.println(-(list.size()-(i)-a));
            resList.add(list.get(-(list.size()-(i)-a)));
            }
        }
         System.out.println(resList);
       }else{
        System.out.println("Shift value should be less than array size");
      }
    }
}
Left shift in java using java 8


import java.util.*;

class HelloWorld {
    public static void main(String[] args) {
        List<String> list= new ArrayList<>();
        list.add("akash");
        list.add("roopesh");
        list.add("rahul");
        list.add("anubhav");
        System.out.println(list);
        int a=2;
        if(a<=list.size()){
        List<String> resList= new ArrayList<>();
        for(int i=0; i<list.size();i++){
            if(i<list.size()-a){
            resList.add(list.get(i+a));
            }else if(i<list.size()){
                System.out.println(-(list.size()-(i)-a));
            resList.add(list.get(-(list.size()-(i)-a)));
            }
        }
         System.out.println(resList);
       }else{
        System.out.println("Shift value should be less than array size");
      }
    }
}
一曲爱恨情仇 2024-12-20 01:50:51

这样就可以了

public static void rotate(int[] nums) {

    int n = nums.length;
    int temp = nums[n - 1];

    for (int i = n - 1; i >= 0; i--) {
        if (i > 0) {
            nums[i] = nums[i - 1];
        } else {
            nums[i] = temp;
        }
    }
    System.out.println(Arrays.toString(nums));
}

This way it would work

public static void rotate(int[] nums) {

    int n = nums.length;
    int temp = nums[n - 1];

    for (int i = n - 1; i >= 0; i--) {
        if (i > 0) {
            nums[i] = nums[i - 1];
        } else {
            nums[i] = temp;
        }
    }
    System.out.println(Arrays.toString(nums));
}
固执像三岁 2024-12-20 01:50:51
import java.util.Scanner;

public class Shift {

    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);
        int array[] = new int [5];
        int array1[] = new int [5];
        int i, temp;

        for (i=0; i<5; i++) {
            System.out.printf("Enter array[%d]: \n", i);
            array[i] = input.nextInt(); //Taking input in the array
        }

        System.out.println("\nEntered datas are: \n");
        for (i=0; i<5; i++) {
            System.out.printf("array[%d] = %d\n", i, array[i]); //This will show the data you entered (Not the shifting one)
        }

        temp = array[4]; //We declared the variable "temp" and put the last number of the array there...

        System.out.println("\nAfter Shifting: \n");

        for(i=3; i>=0; i--) {
            array1[i+1] = array[i]; //New array is "array1" & Old array is "array". When array[4] then the value of array[3] will be assigned in it and this goes on..
            array1[0] = temp; //Finally the value of last array which was assigned in temp goes to the first of the new array
        }


        for (i=0; i<5; i++) {
            System.out.printf("array[%d] = %d\n", i, array1[i]);
        }

        input.close();

    }

}
import java.util.Scanner;

public class Shift {

    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);
        int array[] = new int [5];
        int array1[] = new int [5];
        int i, temp;

        for (i=0; i<5; i++) {
            System.out.printf("Enter array[%d]: \n", i);
            array[i] = input.nextInt(); //Taking input in the array
        }

        System.out.println("\nEntered datas are: \n");
        for (i=0; i<5; i++) {
            System.out.printf("array[%d] = %d\n", i, array[i]); //This will show the data you entered (Not the shifting one)
        }

        temp = array[4]; //We declared the variable "temp" and put the last number of the array there...

        System.out.println("\nAfter Shifting: \n");

        for(i=3; i>=0; i--) {
            array1[i+1] = array[i]; //New array is "array1" & Old array is "array". When array[4] then the value of array[3] will be assigned in it and this goes on..
            array1[0] = temp; //Finally the value of last array which was assigned in temp goes to the first of the new array
        }


        for (i=0; i<5; i++) {
            System.out.printf("array[%d] = %d\n", i, array1[i]);
        }

        input.close();

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文