代码:
创建一个大顶堆一个小顶堆,大顶堆中保存较大的元素,小顶堆中保存较小的元素。
class MedianFinder {
Queue<Integer> A,B;
public MedianFinder() {
A=new PriorityQueue<>();
B=new PriorityQueue<>((a,b)->b-a);
}
public void addNum(int num) {
if(A.size()!=B.size()){
A.add(num);
B.add(A.poll());
}
else{
B.add(num);
A.add(B.poll());
}
}
public double findMedian() {
return A.size()!=B.size() ? A.peek() : (A.peek()+B.peek())/2.0;
}
}
注意:
PriorityQueue()默认是一个小顶堆
代码:
class Solution {
public boolean isSymmetric(TreeNode root) {
return root==null ? true : recur(root.left, root.right);
}
boolean recur(TreeNode L, TreeNode R){
if(L==null && R==null) return true;
if(L==null || R==null || L.val!=R.val)
return false;
return recur(L.left, R.right) && recur(L.right, R.left);
}
}
代码:
class Solution {
public int singleNumber(int[] nums) {
int[] count = new int[32];
int res=0;
for(int i = 0; i < nums.length; ++i){
for(int j = 0; j < 32; ++j){
count[j] += nums[i] & 1;
nums[i] >>>= 1;
}
}
for(int i = 0; i < 32; ++i){
count[i] %= 3;
}
for(int i = 0; i < 32; ++i){
res <<= 1;
res |= count[31-i];
}
return res;
}
}
注意
1.>>:带符号右移 >>>:无符号右移
代码:
算法思想
class Solution {
public int countDigitOne(int n) {
int digit=1, res=0, high = n/10, cur = n%10, low = 0;
while(high !=0 || cur != 0){
if(cur==0){
res += high*digit;
}else if(cur==1){
res += high*digit + low + 1;
}else{
res += (high+1)*digit;
}
low += cur*digit;
cur=high%10;
high/=10;
digit*=10;
}
return res;
}
}
代码:
算法思想
class Solution {
public int add(int a, int b) {
while(b!=0){
int c=(a&b)<<1;
a=a^b;
b=c;
}
return a;
}
}
|