今日LeetCode 打卡

今日LeetCode 打卡 x的平方根这道很简单但是直接暴力会超时所以可用使用二分查找来快速秒掉然后要注意的就是判断大小的时候不要使用mid*mid target因为会溢出直接使用mid x / mid替代具体代码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; } }用栈实现队列这道也是比较简单直接两个栈模拟就行了具体做法就是每次需要取队头元素的时候就直接将元素倒到另一个栈中操作完再倒回来具体代码class MyQueue { StackInteger sta1 new Stack(); StackInteger 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; } }字符串相乘这道也是比较简单主要可以通过规律来找到可以发现就是将num1[i] * nums[j] 的乘积累加到 ans[ij] 位置就行了具体代码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[ij] 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 nm-1; i 0; i --) { if (sb.isEmpty() ans[i] 0) continue; sb.append(ans[i]); } return sb.toString(); } }