简单难度 leetcode 总结

38.报数

自己思路:每一个字符串都由上一个字符串得出,想到了用递归的方法,代码如下:

class Solution {
    public String countAndSay(int n) {
        String s = getS(n);
        return s;
    }
    public static String getS(int n){
        if(n == 1)            //如果 n 为1,直接返回"1"
            return "1";
        else{
            String s1 = getS(n - 1); //递归调用
            int count = 1;           //初始化
            String s = "";
            int pre = s1.charAt(0) - 48;
            for(int i = 1 ; i < s1.length() ; i++){
                if(pre == s1.charAt(i) - 48){
                    count++;
                }else{
                    s = s + count + pre;
                    pre = s1.charAt(i) - 48;
                    count = 1;
                }
            }
            s = s + count + pre;
            return s;
        }
    }
}

运行之后可以通过,但是时间过长,看了别人的代码发现可以直接用循环解决。并且用StringBuilder类可以比用String类显著的缩短运行时间 。代码如下:

class Solution {
    public String countAndSay(int n) {
        StringBuilder ans = new StringBuilder();
        ans.append("1");
        for(int i = 2 ; i <= n ; i++){
            //遍历上一个字符串
            String s = new String(ans); //用s接收上一个字符串
            ans.delete(0 , ans.length());//清空ans
            int count = 0;
            char pre = s.charAt(0);
            for(char c : s.toCharArray()){
                if(pre == c){
                    count++;
                }else{
                    ans.append(count);
                    ans.append(pre);
                    pre = c;
                    count = 1;
                }
            }
            ans.append(count);
            ans.append(pre);
        }
        return ans.toString();
    }
   
}

509.斐波那契数

自己思路:利用简单的递归即可,但是时间太长。更快的方法是用循环。

class Solution {
    public int fib(int N) {
        if(N == 0)
            return 0;
        if(N == 1)
            return 1;
        else{
            return fib(N-1) + fib(N-2);
        }
    }
}

1122.数组的相对排序

解题思路:这道题利用了桶排序,先用一个桶存储arr1中的元素,再利用arr2将其取出,然后把桶中的元素按顺序取出来。

class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] bucket = new int[1001];

        for(int i = 0 ; i < arr1.length ; i++){
            bucket[arr1[i]]++;
        }
        int idx = 0;
        for(int i = 0 ; i < arr2.length ; i++){
            while(bucket[arr2[i]] > 0){
                bucket[arr2[i]]--;
                arr1[idx++] = arr2[i];
            }
        }

        for(int i = 0 ; i < bucket.length ; i++){
            while(bucket[i] > 0){
                bucket[i]--;
                arr1[idx++] = i;
            }
        }
        return arr1;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值