0
点赞
收藏
分享

微信扫一扫

力扣算法学习day04-2

大师的学徒 2022-01-24 阅读 44

文章目录

力扣算法学习day04-2

202-快乐数

题目

image-20220124161517457

代码实现

class Solution {
    // public boolean isHappy(int n) {
    //     int sum = n;
    //     int temp = 0;// 临时变量
    //     int bitIndex = 0;//sum的长度,即有多少位
    //     int bitValue = 0;
    //     HashSet<Integer> set = new HashSet<>();

    //     while(true){
    //         // 当sum变为1时,则为快乐数。
    //         if(sum == 1){
    //             return true;
    //         }

    //         // 判断是否存在,存在则说明不是快乐数,不存在则存储,然后继续。
    //         if(set.contains(sum)){
    //             return false;
    //         } else{
    //             set.add(sum);
    //         }

    //         // 由题意变化
    //         bitIndex = (sum + "").length();
    //         temp = sum;
    //         sum = 0;// 将sum置零
    //         // 计算新的平方和。
    //         for(int i = 1;bitIndex > 0;bitIndex--,i *= 10){
    //             bitValue = temp / i % 10;
    //             sum += bitValue * bitValue;
    //         }
    //     }
    //     // 2 4 16 37 58 89 145 42 20 2
    // }


    // 取位改良版,速度快一点
    public boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while (n != 1 && !record.contains(n)) {
            record.add(n);
            // 获取新的n值
            n = getNextNumber(n);
        }
        return n == 1;
    }
    private int getNextNumber(int n) {
        int sum = 0;
        while (n > 0) {
            sum += ((n % 10) * (n % 10));
            n = n / 10;
        }
        return sum;
    }

    
}

376-摆动序列

题目

image-20220124175853635

代码实现

class Solution {
    // 贪心
    public int wiggleMaxLength(int[] nums) {
        if (nums != null && nums.length <= 1) {
            return nums.length;
        }

        //后差值,即当前差值
        int curDiff = 0;
        //前差值
        int preDiff = 0;
        int count = 1;

        for (int i = 1; i < nums.length; i++) {
            //求得当前差值
            curDiff = nums[i] - nums[i - 1];

            //如果当前差值和上一个差值为一正一负
            //等于0的情况表示假设初始preDiff=0,由于之后的preDiff的成立判断都是有差值的,
            //所以这里preDiff<=0只针对了第一个,后面的的preDiff逻辑上使得不为零,不影响题意。
            if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) {
                count++;
                preDiff = curDiff;
            }
        }
        return count;
    }
}
举报

相关推荐

0 条评论