• 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:
    ");
    	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
    ", 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:
    ");
    	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
    ", 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];
    		}
    	}
    }
    
  • 相关阅读:
    自动换行的两种代码(C#)
    C#的SubString(int start,int end);
    php数组添加元素的方法
    php通过生成动态变量(变量名中还有变量)
    php定义空的数组
    php的$GLOBALS例子
    WINCRIS的使用
    java的PreparedStatement中使用like时的问题
    php发送get请求
    在HTML中使用object和embed标签插入视频
  • 原文地址:https://www.cnblogs.com/stardujie89/p/4795128.html
Copyright © 2020-2023  润新知