Adjust the disordered sequence to an ordered sequence without repeating elements

Idea analysis: First sort the sequence, then define a pointer to the beginning of the sequence, and search backwards one by one until the pointer points to the end of the sequence. The pointer compares whether the current element is equal to the next element (repetition), removes the first element when it is equal, multiplies the second element, and reorders the updated sequence; when it is not equal, the pointer moves to the right.

   /**
     * 功能:将无序序列调整为无重复元素的有序序列
     * 去重规则:重复元素的第一个删除,第二个倍乘
     * 说明:可以使用Arrays.asList(...)将数组转为List;
     * @param lists 无序序列
     * @return 无重复元素的有序序列
     */
    public static List<Long> print(ArrayList<Long> lists) {
    
    
        Collections.sort(lists); // 让初始数据有序
        int i = 0;
        while (true) {
    
    
            if (i == lists.size() - 1) {
    
    
                break;
            }
            int l = i + 1; // 相邻比较
            if (lists.get(i).equals(lists.get(l))) {
    
    
                // 移除两个数,添加一个数
                lists.remove(i);
                lists.add(lists.remove(i) * 2);
                Collections.sort(lists); // 数据更新之后需要重排序
            } else {
    
    
                i = l; // 右移
            }
        }
        return lists;
    }

Guess you like

Origin blog.csdn.net/for62/article/details/107669651