zoukankan      html  css  js  c++  java
  • 约瑟夫环问题

    n个人编号为1,2…n,每次数到m,编号为m的人就退出,问最后留下的人的编号是多少

    package com.lxm.algorithm;
    import java.util.Scanner;
    public class YSF
    {
        public static void main(String[] args)
        {
                Scanner scanner = new Scanner(System.in);
                while(scanner.hasNext())
                {
                    int n = scanner.nextInt();
                    int m = scanner.nextInt();
                    int result = ysf(n,m);
                    System.out.println(result);
                }
    
    
        }
    
        public static int  ysf(int n, int m)
        {
            //initialize array
            int[] data  = new int[n];
            for(int i=0;i<n;i++)
            {
                data[i] = i+1;
            }
    
    
            int left = n;//lasted people
            int index = -1;
            int num=0;
    
            while(left>1)
            {
                    index =( index+1)%n;
                    if(data[index]!=0)
                    {
                        ++num;
                        if(num==m)
                        {
                            data[index] = 0;
                            --left;
                            num=0;
                        }
                    }
            }
            for(int i=0;i<n;i++)
            {
                if(data[i]!=0)
                {
                    return i+1;
                }
            }
    
            return -1;
    
        }
    }
  • 相关阅读:
    事务的隔离级别
    事务的隔离
    事务简介
    leetcode647
    leetcode394
    leetcode96
    leetcode814
    leetcode738
    leetcode621
    leetcode763
  • 原文地址:https://www.cnblogs.com/yldf/p/6249880.html
Copyright © 2011-2022 走看看