Leetcode: tips

1. return it modulo 10^9 + 7 to prevent large result:

=>

int mod = 1_000_000_007; 
then result %= mod 

2. Top-down memorization:
memo几维一般看dfs()里面有几个变量+1,但有的时候dfs()有一个变量全部都+1,
譬如:
    if(i < len1 && s3.charAt(index) == s1.charAt(i)){
          ans |= dfs(len1,len2,len3,s1,s2,s3,i+1,j,index+1,memo);
        }
        if(j < len2 && s3.charAt(index) == s2.charAt(j)){
          ans |=  dfs(len1,len2,len3,s1,s2,s3,i,j+1,index+1,memo);
        }

这个时候memo只用记录i和j,不用记录index

3.  lst.add(Arrays.asList(nums[l],nums[r],nums[i])); 

4. Integer 之间不能 ==,永远是false。改进: a.intValue() == b.intValue() // a,b are Integers 

5. List<Integer> to int[]:  res.stream().mapToInt(i->i).toArray(); 

List<int[]> => int[][] res.toArray(new int[res.size()][]); 

int[][] => List<int[]>  List<int[]> lst = new ArrayList<>(Arrays.asList(arr));// new ArrayList is necessary

想把in[] reverse => 必须是Integer[] 才能用  Collections.reverse(Arrays.asList(cols)); 

6. char default value is '\u0000'

    char可以放进 int[] mappingDictStoT = new int[256]; // 256 include all valid ascii character

    char <-> String 

 char[] sarr = s.toCharArray();
 String.valueOf(sarr)
String.valueOf(sarr[i]).repeat(3);

 7. Arraylist & linkedlist里面可以放int,放进去的保持int类型即可。(会自动) 

ArrayList<int[]> res = new ArrayList<>();
res.add(intervals[0]);

ArrayList also can use  .contains()  but cost O(n) 

8. LinkedList 里面方法名叫:add(), poll() <和pop比,pop会报错,poll返回null>,peek

     Deque是addLast,addFirst,pollLast,pollFirst

9. Int to Double: 

Double d= new Double(i);//first way.
Double d2=Double.valueOf(i);//second way.

int < long < double, sum的时候用long存,最后转换成double比较省空间

10. HashMap -> for each we use  Map.Entry<String,Double> en: map.entrySet() 

11. Pair : 

Pair<Integer,Integer> p = new Pair<>(row, column);
p.getKey();
p.getValue();

 checkerboard:用 Pair<Integer,Integer>[] 代表

12. PriorityQueue

min-heap:  PriorityQueue<Integer> minheap = new PriorityQueue<>((a,b)->a.compareTo(b)); 

method: poll() rather than pop()

TC: offer() & poll() takes  O(logN) 

13. StringBuilder : how to clear ?   sb.setLength(0); 

14. when calculating Space Complexity,  SC only takes O(N) instead of O(N^2)

for( n times){
   create a new map
   for( n times){
       put into the map
    }    
}

 15. SC of Arrays.sort() is O(logN) in Java

16. HashSet<Character> can use  .equals()  to compare 

If we need to compare Set consisting of Integer, we can use ArrayList<Integer> -> Collections.sort() -> .equals()

17. Arrays.toString(row) 

18. max in an array :  Arrays.stream(piles).max().getAsInt(); 

19. char to int is (c - '0') not (int)c 

20. combinations if each for-loop start from i+1 to 9

TC: 

confused??? #77

 

 

 21. Math.random [0,1)

 (int)(Math.random() * lst.size()); 

 22. ArrayList.set(index, val) => use set to change value

 

posted @ 2023-07-03 02:39  PEAR2020  阅读(8)  评论(0编辑  收藏  举报