构造环形链表或者直接List解决

约瑟夫问题I

http://www.nowcoder.com/questionTerminal/11b018d042444d4d9ca4914c7b84a968

链表

public class Joseph {
    static class ListNode {
         int val;
         ListNode next = null;

         ListNode(int val) {
             this.val = val;
         }
     }
     public static int getResult(int n, int m) {
         ListNode head = new ListNode(1);
         ListNode p = head;
         for (int i = 1; i < n; i++) {
             p.next = new ListNode(i + 1);
             p = p.next;
         }
         p.next = head;
         while(head.next!=head){
             for (int i = 0; i < m - 2; i++) {
                 head = head.next;
             }
             head.next = head.next.next;
             head = head.next;
         }
         return head.val;
     }
}

List

import java.util.*;

public class Joseph {
    public int getResult(int n, int m) {
        // write code here
        ArrayList<Integer> list = new ArrayList<>();
        for(int i = 0; i<n;i++){
            list.add(i + 1);
        }
        int flag = 0;
        while(list.size()!=1){
            for (int i = 0; i < m-1; i++) {
                if(flag == list.size() - 1) {
                    flag = 0;
                }else {
                    flag++;
                }
            }
            list.remove(flag);
            if(flag == list.size()) flag = 0;
        }
        return list.get(0);
    }
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务