zoukankan      html  css  js  c++  java
  • [原]《面试题精选》14.圆圈中最后剩下的数字

    题目:n个数字(0,1,…,n-1)形成一个圆圈,从数字0开始,每次从这个圆圈中删除第m个数字(第一个为当前数字本身,第二个为当前数字的下一个数字)。当一个数字删除后,从被删除数字的下一个继续删除第m个数字。求出在这个圆圈中剩下的最后一个数字。


    分析:这是一道约瑟夫环问题。思路就是按照提中的步骤去执行,很明显用到的数据结构是循环双向链表,关键是循环双链表的实现。见:Stacks,Queues,Linked Lists

    public class LastNum{
    	public static void main(String args[]){
    		fun(7,2) ;
    	}
    	public static void fun(int n,int m){
    		MyCircularLinkedList list = new MyCircularLinkedList() ;
    		for(int i=0;i<n;i++){
    			list.insert(i) ;
    		}
    		MyNode temp = list.first ;
    		while(list.N!=1){
    			for(int j=0;j<m-1;j++){
    				temp = temp.next ;
    			}
    			list.del(temp) ;
    			temp = temp.next ;
    			
    		}
    		System.out.println(list.first.key) ;
    	}
    }
    
    class MyCircularLinkedList{
    	MyNode first ;
    	MyNode last ;
    	int N = 0 ;
    	
    	public void insert(int x){
    		MyNode newNode = new MyNode(x) ;
    		if(first == null){
    			first = newNode ;
    			last = newNode ;
    			first.next = last ;
    			last.next = first ;
    			last.pre = first ;
    			first.pre = last ;
    			N++ ;
    		}else{
    			newNode.next = first ;
    			first.pre = newNode ;
    			last.next = newNode ;
    			newNode.pre = last ;
    	
    			last = newNode ;
    			N++ ;
    		}
    	}
    	
    	public void del(MyNode node){
    		if(N==1){
    			first = first ;
    			last = last ;
    		}
    		if(N>1){
    			if(node==first){
    				first = node.next ;
    			}
    			if(node==last) last = node.pre ;
    			
    			node.pre.next = node.next ;
    			node.next.pre = node.pre ;
    		}
    		N--;
    	}
    }
    class MyNode{
    	int key ;
    	MyNode next ;
    	MyNode pre ;
    	
    	public MyNode(int x){
    		key = x ;
    	}
    }


    作者:SpeedMe 发表于2014-4-16 20:20:28 原文链接
    阅读:95 评论:0 查看评论
  • 相关阅读:
    python学习笔记 day14 各种推导式
    python学习笔记 day14 生成器表达式
    python学习笔记 day14 生成器进阶(二)
    python学习笔记 day14 生成器进阶
    python学习笔记 day13 迭代器
    python 学习笔记 day12 作业讲解--员工信息表
    PAT L3-020 至多删三个字符
    2019省赛训练组队赛3.26周二---FJUT 2016
    PAT L3-007 天梯地图
    POJ 2234 Matches Game
  • 原文地址:https://www.cnblogs.com/huanglei/p/3677690.html
Copyright © 2011-2022 走看看