今日LeetCode 摸鱼打卡

x的平方根

这道很简单,但是直接暴力会超时,所以可用使用二分查找来快速秒掉

然后要注意的就是,判断大小的时候不要使用mid*mid == target,因为会溢出,直接使用mid == x / mid替代

具体代码:

java 复制代码
class Solution {
    public int mySqrt(int x) {
        if (x == 0) return 0;
        int l = 1;
        int r = Integer.MAX_VALUE;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            if (mid == x / mid) return mid;
            if (mid > x / mid) r = mid - 1;
            if (mid < x / mid) l = mid + 1;
        }
        return l - 1;
    }
}

用栈实现队列

这道也是比较简单,直接两个栈模拟就行了

具体做法就是每次需要取队头元素的时候就直接将元素倒到另一个栈中,操作完再倒回来

具体代码:

java 复制代码
class MyQueue {

    Stack<Integer> sta1 = new Stack();
    Stack<Integer> sta2 = new Stack();

    public MyQueue() {}
    
    public void push(int x) {
        sta1.push(x);
    }
    
    public int pop() {
        return helper(2);
    }
    
    public int peek() {
        return helper(1);
    }
    
    public boolean empty() {
        return sta1.isEmpty();
    }

    // pop-2 peek-1  
    private int helper(int flag) {
        while (sta1.size() > 1) {
            sta2.push(sta1.pop());
        }
        int res = sta1.peek();
        if (flag == 2) sta1.pop();
        while (!sta2.isEmpty()) {
            sta1.push(sta2.pop());
        }
        return res;
    }
}

字符串相乘

这道也是比较简单,主要可以通过规律来找到

可以发现就是将num1i * numsj 的乘积累加到 ansi+j 位置就行了

具体代码:

java 复制代码
class Solution {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) return "0";
        int n = num1.length();
        int m = num2.length();
        int[] ans = new int[n + m];
        for (int i = 0; i < n; i ++) {
            int a = num1.charAt(n-i-1) - '0';
            for (int j = 0; j < m; j ++) {
                int b = num2.charAt(m-j-1) - '0';
                ans[i+j] += a * b;
            }
        }

        int carry = 0;
        for (int i = 0; i < n + m; i ++) {
            int sum = ans[i] + carry;
            ans[i] = sum % 10;
            carry = sum / 10;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = n+m-1; i >= 0; i --) {
            if (sb.isEmpty() && ans[i] == 0) continue;
            sb.append(ans[i]);
        }
        return sb.toString();
    }
}
相关推荐
悟道书生27 分钟前
hashMap/hashSet/hashCode详解
java
nice_lcj5202 小时前
依赖注入的三种方式:构造器、Setter、字段怎么选
java·spring·面试·依赖注入·字段注入·构造器注入
噢,我明白了2 小时前
实际项目导出方式应用
java·状态模式·导出
青少儿编程课堂3 小时前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
جيون داد ناالام ميづ3 小时前
七、MyBatis 源码剖析:核心流程拆解(初始化 + SQL 执行)
java·sql·mybatis
ClkLog-开源埋点用户分析4 小时前
【产品说明】【埋点分析】ClkLog 商业版 Java 运行环境安全更新说明
java·开发语言
秋饼4 小时前
Spring Framework 7 内置弹性实战:@Retryable 语义翻转、虚拟线程流量放大与 LLM 网关治理
java·ai·技术分享·后端开发
RuoyiOffice4 小时前
Flowable只是起点:一套OA背后的单据、资源与协作设计
java·vue.js·spring boot·flowable·企业管理·oa·ruoyi office
yuzhiboyouye4 小时前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql