有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java算法拼接出列表的一部分,将其反转并覆盖上一部分

我想知道如何使用Java尽可能轻松地完成此任务:

  1. 拼接出ArrayList的一部分(按索引)
  2. 反转此接头
  3. 使用拼接/反转的索引范围覆盖原始列表中的索引范围

例如,我有一个包含以下数字的列表:

[3,2,8,9]

拼接:

[2,8,9]

倒过来:

[9,8,2]

把它重新组合起来:

[3,9,8,2]

致意


共 (1) 个答案

  1. # 1 楼答案

    下面是您的需求的通用代码,复杂性为O(n)——

    <E> List<E> spliceAndReverse(List<E> list, int startIndex, int endIndex){
            while(startIndex < endIndex){
                E e = list.get(startIndex);
                list.set(startIndex, list.get(endIndex));
                list.set(endIndex, e);
                startIndex++;
                endIndex ;
            }   
            return list;
        }
    

    我们也可以使用子列表,下面是代码-

    static <E> List<E> spliceAndReverseUsingSubList(List<E> list, int startIndex, int endIndex){
            List<E> subList =  list.subList(startIndex, endIndex+1);
            Collections.reverse(subList);
            List<E> resultList = new ArrayList<>(list.subList(0, startIndex));
            resultList.addAll(subList);
            if(list.size() != endIndex+1){
            resultList.addAll(list.subList(endIndex+1, list.size()));
            }
            return resultList;
        }
    


    参见此处示例- http://blog.deepaktripathi.in/uncategorized/reverse-arraylist-between-2-given-indexes/

    注意-在平台上提问之前,请确保您已经试过了