【问题标题】:Moving from first to last in an array when last can be smaller than the first当最后一个可以小于第一个时,在数组中从第一个移动到最后一个
【发布时间】:2021-10-05 01:58:11
【问题描述】:

在 Java 中,当最后一个可以小于第一个时,有没有更好的方法来完成从数组中的第一个到最后一个的移动?这是我目前在我的双端队列实现中使用的:

public void printDeque() {
    int start = nextFirst + 1, end = nextLast - 1;
    if (start >= end) {
        for (int i = start; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }

        for (int i = 0; i <= end; i++) {
            System.out.print(list[i] + " ");
        }
    } else {
        for (int i = start; i <= end; i++) {
            System.out.print(list[i] + " ");
        }
    }

    System.out.println();
}

【问题讨论】:

    标签: java algorithm data-structures deque


    【解决方案1】:

    我建议您创建一个ArrayList 实例,将每个项目从nextFirst 附加到nextLast(以大小为模)并显示结果列表:

    import java.util.*;
    
    public class HelloWorld {
        static String[] array = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
        
        public static void deque(int nextFirst, int nextLast) {
            nextFirst %= array.length; // Simple security measure
            nextLast %= array.length; // Simple security measure
            
            int id = nextFirst;
            if (nextLast < nextFirst)
                nextLast += array.length;
            
            ArrayList<String> list = new ArrayList<>();
            while (id <= nextLast)
                list.add(array[id++ % array.length]);
            
            String[] result = list.toArray(new String[list.size()]);
            System.out.println(String.join(" ", result));
        }
        
        public static void main(String... args) {
            deque(7, 2);
        }
    }
    

    【讨论】:

      【解决方案2】:

      我意识到在遍历过程中,lastIndex 并不重要,因为对象是连续放置的,因此我们可以从第一个位置开始并继续直到遇到 null。

      然后我们可以从 0 开始并继续直到我们得到空值,同时保持小于第一个位置。这种情况仅在 first > last 时出现。

      代码如下:

      private int getFirstIndex() {
          int first = nextFirst + 1;
          if (first == items.length) {
              first = 0;
          }
          return first;
      }
      
      public void printDeque() {
          int firstIndex = getFirstIndex()
          for (int i = firstIndex; i < items.length && items[i] != null; i++) {
              System.out.print(items[i] + " ");
          }
          for (int i = 0; i < firstIndex && items[i] != null; i++) {
              System.out.print(items[i] + " ");
          }
          System.out.println();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-08
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        • 1970-01-01
        • 2018-04-06
        • 1970-01-01
        相关资源
        最近更新 更多