根据步长,删除对应的数据,一直循环,直到只剩最后一个数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fhm6100411074/article/details/79888590

根据步长,删除对应的数据,一直循环,直到只剩最后一个数据,请问最后一个数据是什么?

例如:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 有这组数据组成一个圈,每次删除第7个数据,删除后,从第8个数据开始重新计数,依然是删除第7个数据,如此循环,直到只剩一个数据,求最后剩余的数据是什么?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 只要设置步长和初始删除的索引位置,即可实现任意步长的删除
 *
 */
public class Test {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12));
		// 步长,每次删除第7个数字
		int step = 7;
		// 第一次删除的位置
		int removeIndex = step - 1;
		// 当前索引
		int curIndex = -1;
		while (list.size() > 1) {
			list.remove(removeIndex);
			// 判断是否重新开始遍历
			boolean head = false;
			curIndex = removeIndex;
			for (int i = 0; i <= step - 1; i++) {
				if (!head) {
					curIndex = (removeIndex + i) % list.size();
				} else {
					curIndex = (curIndex + 1) % list.size();
				}
				if (curIndex == 0) {
					head = true;
				}
			}
			removeIndex = curIndex;
		}
		System.out.println(list);
	}
}

二、优化版:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 只要设置步长和初始删除的索引位置,即可实现任意步长的删除
 *
 */
public class Test {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 6));
		// 步长,每次删除第7个数字
		int step = 3;
		// 第一次删除的位置
		int removeIndex = step - 1;
		// 当前索引
		int curIndex = -1;
		while (list.size() > 1) {
			list.remove(removeIndex);
			curIndex = removeIndex;
			for (int i = 0; i <= step - 1; i++) {
				if (i == 0)
					continue;
				curIndex = (curIndex + 1) % list.size();
			}
			removeIndex = curIndex;
		}
		System.out.println(list);
	}
}




猜你喜欢

转载自blog.csdn.net/fhm6100411074/article/details/79888590