Skip to content
Shen Yunlong edited this page Feb 27, 2015 · 44 revisions

Leetcode刷题总结

一般的解题思路:

  1. 当问题可以分解为相同(较小规模)的子问题时,可以考虑使用递归

关于如何设计递归函数

stackoverflowHow to perform a recursive search?

Result M(Problem prob)
{
    if (<problem can be solved easily>)
        return <easy solution>;
    // The problem cannot be solved easily.
    Problem smaller1 = <reduce problem to smaller problem>
    Result result1 = M(smaller1);
    Problem smaller2 = <reduce problem to smaller problem>
    Result result2 = M(smaller2);
    ...
    Result finalResult = <combine all results of smaller problem to solve large problem>
    return finalResult;
}

  1. 二叉树相关的问题,一般都可以考虑使用递归

递归(recursive)与迭代(iterative)solution !


  1. 链表相关的问题

  1. 数组相关的问题

为了避免无谓的重复移动数组元素(插入/删除某个元素时), 可以通过数组靠后的元素逐个覆盖前面的元素(时间复杂度O(N)), 从后向前合并(时间复杂度O(M+N))


  1. 字符串相关的问题

例如:Longest Common Prefix, Count and Say

字符串转整数:String to Integer (atoi) (去除开头的white-space字符;系统调用isdigit(), **isspace()**等)


  1. 动态规划 DP(Dynamic Programming

  1. 贪心

  1. 回溯Backtracking

  1. 分治

  1. 二分/折半

  1. Hash表Two Pointers

几道相同类型的题目:Two Sum , 3Sum , 3Sum Closest , 4Sum

Hash Table: Anagrams (关于字符串hash:各种字符串Hash函数比较)



  1. 数据结构

  1. 一些常见的排序算法
Sorting Algorithm Best Average Worst
QuickSort O(nlogn) O(nlogn) O(n^2)
MergeSort O(nlogn) O(nlogn) O(nlogn)
HeapSort O(nlogn) O(nlogn) O(nlogn)

三种线性排序算法 计数排序、桶排序与基数排序


  1. 其他一些技巧性方法
  • 相同的数**异或(^)**结果为0:Single Number

  • 循环获取整数的每一位:Reverse Integer

      while(x != 0) {
          int value = x % 10;
          x = x / 10;
      }
    
  • double类型数据与0进行比较:

      if( fabs(double_number) < 10e-7 ) {
          ......
      }
    

Clone this wiki locally