约瑟夫环经典问题

public static void main(String[] args) {
        System.out.println(JSON.toJSON(kingRing(41, 3)));
    }

    //链表实现-删除效率高-不需要复制或移动元素
    public static Integer[] kingRing(int count, int kill) {
        Integer[] array = new Integer[Math.min(count, kill - 1)];
        int index = 0;
        if (count < kill) {
            //自增妙用
            for (int i = 0; i < count; i++) {
                array[index++] = index;
            }
        }
        List<Integer> link = new LinkedList();
        for (int j = 0; j < count; j++) {
            link.add(j + 1);
        }
        int number = 0;
        int pointer = 0;
        while (kill <= link.size()) {
            number++;
            if (pointer > link.size() - 1) {
                pointer = 0;
            }
            if (number % kill == 0) {
                link.remove(pointer);
                continue;
            }
            pointer++;
        }
        return link.toArray(array);
    }

 

约瑟夫环经典问题

上一篇:QT使用WOL实现远程一键开机(局域网)


下一篇:单词梯问题