【问题标题】:Shift elements circularly in array by n将数组中的元素循环移动 n
【发布时间】:2015-12-05 22:58:55
【问题描述】:

我正在尝试使用一种方法将数组的元素向左移动 n(某个随机数)。困难在于将数组开头的元素与末尾的元素交换。到目前为止,这是我的代码。

问的其他数组问题与这个不同。

public class Shifty {

    private int[] datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

    public Shifty() {
        datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
    }

    public int shift(int position) {
        int tmp = 0;
        int[] tmp1 = new int[12];
        for (int i = 0; i <= 12; i++) {
            if (i < position) {

                  tmp1[12-position] = this.datas[i];

            } else {
                this.datas[i] = this.datas[i+1];
                            }
            for  (int j = 12-position; j <= 12; j++){
                this.datas[j] = tmp1[j];
            }
        }

        return position;
    }

    public void display() {
        System.out.println(Arrays.toString(this.datas));
        System.out.println();
    }
}

【问题讨论】:

标签: java arrays


【解决方案1】:

您可以充分利用模运算。

public void shift(int n) {
  int[] temp = new int[datas.length];
  for (int i = 0; i < temp.length; i++) {
    temp[i] = datas[(i + n) % temp.length];
  }
  datas = temp;
}

【讨论】:

    【解决方案2】:

    由于您显然不需要就地进行移位并且可以使用临时数组,因此解决方案非常简单:

    public class Shifty {
    
        private int[] datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
    
        public Shifty() {
            datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        }
    
        public int shift(int position) {
            final int len = datas.length;
            int[] tmp = Arrays.copyOf(datas, position);
            System.arraycopy(datas, position, datas, 0, len - position);
            System.arraycopy(tmp, 0, datas, len - position, position);
            return position;
        }
    
        public void display() {
            System.out.println(Arrays.toString(this.datas));
            System.out.println();
        }
    }
    

    这仅适用于使用 datas 的合法下标的参数值的 shift 调用。如果要处理负值或大于datas.length 的值,则需要将position 减少到适当的范围。请注意,由于这是循环移位,因此您可以在此处使用模运算,因为 shift(position) 和 shift(position * n*datas.length) 对于任何整数值 n 都应该产生相同的结果。

    【讨论】:

      猜你喜欢
      • 2012-08-25
      • 2017-02-28
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      相关资源
      最近更新 更多