其他分享
首页 > 其他分享> > n个数排好,从1开始数,数到3的为幸运数,出列,重新再从1数到3,数到最后,接着从头数,求最后一个幸运数是多少?

n个数排好,从1开始数,数到3的为幸运数,出列,重新再从1数到3,数到最后,接着从头数,求最后一个幸运数是多少?

作者:互联网

package API;

import java.util.*;

/**
 * Author:jinpma
 * Date :2019/9/14
 */
/*
1.名称:n个数排好,从1开始数,数到3的为幸运数,出列,重新再从1数到3,数到最后,接着从头数,求最后一个幸运数是多少?
2.分析:递归函数,终止条件:集合长度<1
3.实现:
    1).定义一个集合(长度可变,内容可变),出列==从集合中将次数删除,集合用来存储非幸运数
    2).不管n多大,第一遍出列的幸运数肯定是3.6.9.12···
    3).删除幸运数后的新集合的0索引上的值在1-3中位置和上一遍集合长度有关
        1.上一遍集合长度%3==0,本遍集合0索引对应值在1-3中的位置为1
        2.上一遍集合长度%3==1,本遍集合0索引对应值在1-3中的位置为2
        2.上一遍集合长度%3==2,本遍集合0索引对应值在1-3中的位置为3,即幸运数
4.注意:
    1).在一遍搜索幸运数过程中,每删除一个幸运数,集合实时长度都会-1
        所以for循环中判断条件不能用list.size()
    2).  
 */
public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            list.add(i);
        }
        int count = 0;
        for (int index = 0; index < n; index++) {
            if ((index + 1) % 3 == 0) {
                list.remove(index - count);
                count++;
            }
        }
        List<Integer> result = method(list, n);
        System.out.println(result.get(0));
    }

    public static List<Integer> method(List<Integer> list, int m) {
        if (list.size() > 1) {
            int count = 0;
            if (m % 3 == 0) {
                //本遍集合长度,即本遍未删除幸运数之前的集合长度
                //对递归函数而言,即上一遍集合长度
                int n = list.size();
                for (int index = 0; index < n; index++) {
                    if ((index + 1) % 3 == 0) {
                        list.remove(index - count);
                        count++;
                    }
                }
                return method(list, n);
            } else if (m % 3 == 1) {
                //本遍集合长度,即本遍未删除幸运数之前的集合长度
                //对递归函数而言,即上一遍集合长度
                //上一遍集合长度%3==1,本遍集合0索引对应值在1-3中的位置为2
                int n = list.size() + 1;
                for (int index = 0; index < n - 1; index++) {
                    if ((index - 1) % 3 == 0) {
                        list.remove(index - count);
                        count++;
                    }
                }
                return method(list, n);
            } else {
                int n = list.size() + 2;
                for (int index = 0; index < n - 2; index++) {
                    if ((index) % 3 == 0) {
                        list.remove(index - count);
                        count++;
                    }
                }
                return method(list, n);
            }
        }
        return list;
    }
}

标签:count,index,数到,int,list,++,集合,幸运,数是
来源: https://blog.csdn.net/tmax52HZ/article/details/100836315