LeetCode 每日一题 [1447]最简分数

今天的medium题比较简单,AC率67.4%

class Solution {
    public List<String> simplifiedFractions(int n) {

        StringBuilder sb;
        List<String> strList = new ArrayList<>();
        int temp;
        int x;
        int y;

        if(n == 1) {

            return strList;
        }
        if(n == 2) {

            strList.add("1/2");
            return strList;
        }
        for(int i = 2; i<=n;i++) {

            sb = new StringBuilder();
            sb.append(1).append("/").append(i);
            strList.add(sb.toString());

            for(int a = 2; a < i; a++) {

                y = i;
                x = a;
                while(x != 0) {

                    temp = y % x;
                    y = x;
                    x = temp;
                }
                if (y == 1) {

                    sb = new StringBuilder();
                    sb.append(a).append("/").append(i);
                    strList.add(sb.toString());
                }
            }
        }

        return strList;
    }
}

相比于递归和GCD速度和内存消耗能占优势,但是代码很长

posted @ 2022-02-10 15:59  Frank_Z9  阅读(28)  评论(0)    收藏  举报