1.Populating Next Right Pointers in Each Node II(广搜)
解法:
2.Course Schedule II(深搜)
解法:
3.Minimum Height Trees(深搜)
解法:
4.House Robber3(深搜)
解法:
5.Course Schedule,Minimum Height Trees(深搜,都是将图以邻接表的形式存储,然后用一个数组维护)
解法:
vector<unordered_set<int>> adj(n);
adj[edge.second].insert(edge.first);
adj[a].erase(t);
6.Counting Bits(数学原理)
解法:
7.不用+-*/做两数相加(位运算)
解法如代码,java位运算知识<<,>>,^,&等等
//首先看十进制是如何做的: 5+7=12,三步走//第一步:相加各位的值,不算进位,得到2。//第二步:计算进位值,得到10. 如果这一步的进位值为0,那么第一步得到的值就是最终结果。////第三步:重复上述两步,只是相加的值变成上述两步的得到的结果2和10,得到12。////同样我们可以用三步走的方式计算二进制值相加: 5-101,7-111 第一步:相加各位的值,不算进位,得到010,二进制每位相加就相当于各位做异或操作,101^111。////第二步:计算进位值,得到1010,相当于各位做与操作得到101,再向左移一位得到1010,(101&111)<<1。////第三步重复上述两步, 各位相加 010^1010=1000,进位值为100=(010&1010)<<1。// 继续重复上述两步:1000^100 = 1100,进位值为0,跳出循环,1100为最终结果。public class Solution3 { public int Add(int num1,int num2) { while (num2!=0) { int temp = num1^num2; num2 = (num1&num2)<<1; num1 = temp; } return num1; }}
8.不用乘除取模运算的除法(位运算,难点在于边界值,负数比正数多1,所以可以都转化成负数求解)
1 class Solution { 2 public int divide(int dividend, int divisor) { 3 if(dividend == Integer.MIN_VALUE && divisor == -1){ 4 return Integer.MAX_VALUE; 5 } 6 7 boolean isNeg = (dividend < 0) ^ (divisor < 0);//异号为true,同号false 8 if(dividend > 0) dividend = -dividend; 9 if(divisor > 0) divisor = -divisor;10 11 return isNeg? -div(dividend, divisor) : div(dividend, divisor);12 }13 public int div(int divid, int divis){14 15 if(divid > divis) return 0;16 int curSum = divis << 1, prevSum = divis, q = 1;17 18 while(divid <= curSum && curSum < prevSum){19 prevSum = curSum;20 curSum <<= 1; q <<= 1;21 }22 return q + div(divid - prevSum, divis);23 }24 25 }
9.查找指定数在数组中出现的最前和最后的位置(难点在于小技巧)
1 package 查找; 2 3 //34. Find First and Last Position of Element in Sorted Array 4 class Solution2 { 5 public int[] searchRange(int[] nums, int target) { 6 double left = target - 0.5, right = target + 0.5; 7 int l = bs(nums, left), r = bs(nums, right); 8 if(l == r) return new int[]{-1, -1}; 9 return new int[]{l, r-1};10 }11 12 public int bs(int[] nums, double target) {13 int l = 0, h = nums.length-1;14 while(l <= h){15 int m = l + (h - l)/2;16 if(target > nums[m]) l = m+1;17 else h = m-1;18 }19 return l;20 }21 22 public int[] searchRange2(int[] nums, int target) {23 int hi = nums.length - 1;24 int low = 0;25 int[] rs = new int[2];26 // base case27 if(nums == null || nums.length == 0)28 return new int[]{-1, -1 };29 30 //left side31 while(low < hi){32 int mid = low + (hi - low) /2;33 if(target > nums[mid]){34 low = mid + 1;35 }else{36 hi = mid;37 }38 }39 if(target == nums[low]){40 rs[0] = low;41 }else{42 rs[0] = -1;43 }44 45 //right side46 hi = nums.length - 1;47 while(low < hi){48 int mid = (low + (hi - low) /2 ) + 1;49 50 if(target < nums[mid]){51 hi = mid - 1;52 }else{53 low = mid;54 }55 }56 if(target == nums[hi]){57 rs[1] = hi;58 }else{59 rs[1] = -1;60 }61 62 return rs;63 }64 65 }