Java(利用數組模擬雙向迴環鏈表)解決數三去一問題

代碼以下:java

public class Count3Quit {
	public static void main(String[] args) {
		
		//用數組模擬雙向迴環鏈表
		int[] arr = new int[500];
		for (int i = 0; i < arr.length; i++) {
			if (i < arr.length - 1) {
				arr[i] = i + 1;
			} else {
				arr[i] = 0;
			}
		}
		
		int index = 0;
		int count3Num = 0;
		int before = 0;
		while (arr[index] != index) {
			count3Num++;
			if (count3Num == 3) {
				count3Num = 0;
				arr[before] = arr[index];
			}
			before = index;
			index = arr[index];
		}

		System.out.println(arr[index]);
		System.out.println(index);
}
相關文章
相關標籤/搜索