1. 程式人生 > >陣列迴圈右移和約瑟夫環問題

陣列迴圈右移和約瑟夫環問題

1. 把陣列中的每個數迴圈右移n位,要求時間複雜度O(n),空間複雜度O(1)

package cn.lifx.test;

public class RightMove 
{
	public static void main(String[] args)
	{
		int n = 10;
		int m = 3;
		
		int[] arr = new int[n];
		
		for(int i=0; i<arr.length; i++)
		{
			arr[i] = i;
		}
		
		RightMove rm = new RightMove();
		
		rm.Move(arr, m);
		
		rm.Move2(arr, m);
	}
	
	//時間複雜度為O(n),空間複雜度O(1)
	public void Move(int[] arr, int n)
	{
		int len = arr.length-1;
		int mid = arr.length/2;
		
		int temp = 0;
		for(int i=0; i<mid; i++)
		{
			temp = arr[i];
			arr[i] = arr[len-i];
			arr[len-i] = temp;
		}
		
		mid = n/2;
		for(int i=0; i<mid; i++)
		{
			temp = arr[i];
			arr[i] = arr[n-i-1];
			arr[n-i-1] = temp;
		}
		
		mid = (arr.length - n)/2 + n;
		for(int i=n; i<mid; i++)
		{
			temp = arr[i];
			arr[i] = arr[len-i+n];
			arr[len-i+n] = temp;
		}
		
		Display(arr);
	}
	
	//時間複雜度為O(n*m),空間複雜度O(1)
	public void Move2(int[] arr, int n)
	{
		int len = arr.length - 1;
		int temp = 0;
		
		for(int i=0; i<n; i++)
		{
			temp = arr[len];
			for(int j=len; j>0; j--)
			{
				arr[j] = arr[j-1];
			}
			arr[0] = temp;
		}
		
		Display(arr);
	}
	
	public void Display(int[] arr)
	{
		System.out.println();
		for(int i=0; i<arr.length; i++)
		{
			System.out.print(arr[i] + " ");
		}
	}
}

2. n個人圍成一圈,序號依次為0到n-1,從第一個開始報數,到第m個人時他出列,然後從下一個人開始從0計數。問最後一個出列的是誰。

package cn.lifx.test;

import java.util.LinkedList;

public class DeleteNum 
{
	public static void main(String[] args)
	{
		int N = 6;
		int M = 4;
		
		DeleteNum delete = new DeleteNum();
		
		int[] arr = new int[N];
		for(int i=0; i<arr.length; i++)
		{
			arr[i] = i;
		}
		
		delete.Delete(arr, N, M);
		
		LinkedList<String> list = new LinkedList<String>();
		for(int i=0; i<N; i++)
		{
			list.add(i+"");
		}
		
		delete.Delete(list, N, M);
	}
	
	public void Delete(int[] arr, int N, int M)
	{
		boolean[] flags = new boolean[arr.length];
		
		for(int i=0; i<flags.length; i++)
		{
			flags[i] = false;
		}
		
		int sum = 0;
		int count = 0;
		int i = 0;
		
		System.out.print("The deleted numbers are: ");
		
		while(sum != N - 1)
		{
			if(!flags[i%N])
			{
				count++;
				
				if(count == M)
				{
					sum++;
					count = 0;
					flags[i%N] = true;
					System.out.print(arr[i%N] + " ");
				}
			}
			
			i++;
		}
		
		for(i=0; i<flags.length; i++)
		{
			if(!flags[i])
			{
				System.out.println("\nThe last number is : " + arr[i]);
				break;
			}
		}
	}
	
	public void Delete(LinkedList<String> list, int N, int M)
	{
		int i = 0;
		int sum = 0;
		int count = 0;
		
		System.out.print("The deleted numbers are: ");
		
		while(sum != N-1)
		{
			count++;
			
			if(count == M)
			{
				System.out.print(list.remove(i%list.size()) + " ");
				
				i--;
				sum++;
				count = 0;
			}
			
			i++;
			
			if(i == list.size())
			{
				i = 0;
			}
		}
		
		System.out.println("\nThe last number is : " + list.getFirst());
	}
}