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;
}
}
字符串相乘

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

可以发现就是将num1[i] * nums[j] 的乘积累加到 ans[i+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();
}
}