Interview Algorithm

约瑟夫环:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int find(int *arr, int m, int n);

int main(int argc, char* argv[])
{
	int m, n;
	int index;

	printf("Please input the value of m and n:\n");
	fflush(stdout);
	scanf("%d %d", &m, &n);

	int *arr;
	arr = (int*)calloc(n, sizeof(int));
	for (index = 0; index<n; index++)
	{
		arr[index] = index+1;
	}
	printf("The winner is: %d\n", find(arr, m, n));

	free(arr);
	arr = NULL;

	system("pause");
	return 0;
}

int find(int *arr, int m, int n)
{
	int len = n;
	int index, step;
	index = step = 0;

	while(len>1)
	{
		if (arr[index] != 0)
		{
			++step;
			if (step == m)
			{
				arr[index] = 0;
				step = 0;
				len--;
			}
		}
		index = (index+1)%n;
	}

	for (index = 0; index<n; index++)
	{
		if (arr[index] != 0)
		{
			return arr[index];
		}
	}
}

将所有的整数放在负数的前面:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int find(int *arr, int m, int n);

int main(int argc, char* argv[])
{
	int m, n;
	int index;

	printf("Please input the value of m and n:\n");
	fflush(stdout);
	scanf("%d %d", &m, &n);

	int *arr;
	arr = (int*)calloc(n, sizeof(int));
	for (index = 0; index<n; index++)
	{
		arr[index] = index+1;
	}
	printf("The winner is: %d\n", find(arr, m, n));

	free(arr);
	arr = NULL;

	system("pause");
	return 0;
}

int find(int *arr, int m, int n)
{
	int len = n;
	int index, step;
	index = step = 0;

	while(len>1)
	{
		if (arr[index] != 0)
		{
			++step;
			if (step == m)
			{
				arr[index] = 0;
				step = 0;
				len--;
			}
		}
		index = (index+1)%n;
	}

	for (index = 0; index<n; index++)
	{
		if (arr[index] != 0)
		{
			return arr[index];
		}
	}
}
posted @ 2015-09-09 16:26  stardujie  阅读(123)  评论(0编辑  收藏  举报