将一组数组向右移动k位,末尾的要转置移动到数组开始,其中n为数组大小,0<k<n
下面是使用a数组本身完成:
package 数组元素k位右移; /** * 数组向又移动k位。 0<k<n * * @author SeeClanUkyo 将一组数组向右移动k位,末尾的要转置移动到数组开始,其中n为数组大小,0<k<n */ public class ArrayMoveK { public static void main(String[] args) { int k = 3; int[] a = { 1, 2, 3, 4, 5 }; arrayMoveK(a, k); } public static void arrayMoveK(int[] a, int k) { //获取长度 int l = a.length; //获取最大下标值 int maxIndex = l - 1; //for循环使末尾及开始更换位置 for (int i = 0; i < k; i++) { //获取数组最大下标的数值 int last = a[maxIndex]; for (int j = 0; j < maxIndex; j++) { //将数组中的其他元素都右移一位 , 第一次获取时,maxIndex-j为-0为maxIndex本身 a[maxIndex - j] = a[maxIndex - 1 - j]; } //将本次最末尾的数值传递给数组开始 a[0] = last; } //遍历输出新的数组 for (int x : a) { System.out.print(x + " "); } } }
下面是借助第二个数组:(这样的话就简单的多了)
package 数组元素k位右移; /** * 数组向又移动k位。 0<k<n * * @author SeeClanUkyo 将一组数组向右移动k位,末尾的要转置移动到数组开始,其中n为数组大小,0<k<n */ public class ArrayMoveK { public static void main(String[] args) { int k = 3; int[] a = { 1, 2, 3, 4, 5 }; arrayMoveK(a, k); } public static void arrayMoveK(int[] a, int k) { //获取长度 int l = a.length; //获取最大下标值 int maxIndex = l - 1; //for循环使末尾及开始更换位置 for (int i = 0; i < k; i++) { //获取数组最大下标的数值 int last = a[maxIndex]; for (int j = 0; j < maxIndex; j++) { //将数组中的其他元素都右移一位 , 第一次获取时,maxIndex-j为-0为maxIndex本身 a[maxIndex - j] = a[maxIndex - 1 - j]; } //将本次最末尾的数值传递给数组开始 a[0] = last; } //遍历输出新的数组 for (int x : a) { System.out.print(x + " "); } } }
将0置后,不使用新的存储空间
```
package moocstudent.github.io.excelprocessdemo.test;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
/**
* @Author: zhangQi
* @Date: 2022-01-04 9:22
*/
@Slf4j
public class SortedZeroArrDemo {
/**
*
*/
@Test
public void test() {
int arr[] = {0, 1, 3, 0, 2, 8, 0, 0,0, 6, 0, 0, 7};
log.info("排序0前:{}", arr);
int len = arr.length;
//最大下标
int maxIdx = len - 1;
int swapCount = 0;//记录转换0的次数,将抛弃后面几位不进行转换,(因为已经都是0)
for (int i = 0; i <len; i++) {
log.info("i:{}",i);
int ele;
int k;
k = i-swapCount;
log.info("k:{}",k);
if (!(k<=len-swapCount)){
log.info("break");
break;
}
ele = arr[k];
log.info("ele:{}", ele);
if (ele == 0 && k != maxIdx) {
//其它前移(不可声明新数组占用内存,要将数据移动位置,这也是数组作为list底层来删除数据慢于linkedList的原因)
for (int j = k; j < maxIdx; j++) { //when j<len , after j++, j+1 will greater than maxIndex of the arr
log.info("前移的数据:{}", arr[j + 1]);
arr[j] = arr[j + 1];
}
//放置0
arr[maxIdx] = ele;
swapCount++;
}
}
log.info("排序0后:{}", arr);
}
}
```
本文来自博客园,作者:ukyo--君君小时候,转载请注明原文链接:https://www.cnblogs.com/ukzq/p/9175989.html