今日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();
    }
}
相关推荐
这个昵称不容易1 小时前
SpringBoot「衣依」服装销售平台:144个Java文件180个接口,从挑衣服到收货评价整条链路都在
java·springboot·毕设
计算机毕设定制辅导-无忧学长1 小时前
《基于微信小程序的居家医疗陪护预约系统设计与实现》
java·spring boot·微信小程序·uniapp·居家医疗陪护预约系统
文丑颜不良啊3 小时前
LeetCode2221~2240题目解析
java·leetcode
秋饼3 小时前
Computer Use Agent Java 落地实战:感知-行动循环、执行器与安全围栏生产级实现
java·ai·技术分享·后端开发
Navigator_Z3 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH4 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶4 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊5 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊5 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法