- public class DeleteEveryTwo {
- public static void main(String[] args) {
- int index = getLastDeletedIndex(8);
- System.out.println("The last index deleted is " + index);
- }
-
-
- public static int getLastDeletedIndex(int len) {
- if (len <= 0) {
- return -1;
- }
-
- int[] arr = new int[len];
- for (int i = 0; i < len; i++) {
- arr[i] = len;
- }
-
- final int DELFLAG = len + 1;
- int currentSize = len;
- final int STEP = 2;
- int count = 0;
- int lastDelIndex = 0;
- int i = 0;
-
- while (currentSize != 0) {
- if (arr[i] != DELFLAG) {
- if (count++ == STEP) {
- arr[i] = DELFLAG;
- lastDelIndex = i;
- currentSize--;
- count = 0;
- System.out.println("Deleted index is " + i % len);
- }
- }
- i = (i + 1) % len;
- }
- return lastDelIndex;
- }
- }
一个数组,每隔两个数删除一个数,到数组末尾接着从头开始,一直循坏,得出最后删除的一个元素的下标
原文:http://www.cnblogs.com/GodZhe/p/5414809.html