2019-03

作者: 钠非喇肆 | 来源:发表于2019-04-02 11:45 被阅读0次

    3.11

    1. two-sum (easy)
      Q: Given exactly one solution, -> 1 there still can be duplicates 2. exclude that only one of duplicate is the result, which means that both of them or none of them being the result

    A: if there is duplicate, check whether these two integers add up to be the result first, after that, we can add it to hashmap. Briefly, just changing the order is enough.

    1. reverse-integer (easy) (overflow question)
      Q: Given a 32-bit signed integer -> really hard to get every digit and hard to deal with the negative part(wrong)
      A: feeling hard because you want to get all digits immediately but you can get it one by one using %10 and /10

    Q: this is signed integer, and worry about overflow -> just check the final value with Integer.MAX_VALUE (wrong, already overflow)
    A: check one step before final step; when dealing with digit, think of 10 into binary (around 2^3);

    better way to think about overflow, the key part is: after overflow, the final step cannot be recovered back to previous value

    1. palindrome-number (easy)
      int rev = 0;
      while(x > rev) {
      rev = rev * 10 + x % 10;
      x /= 10;
      }
      return (rev == x) || (rev/10 == x);

    2. roman-to-integer (easy)
      this is not a normal traverse, it is about combine two elements or not, so we use while(i<len) i++ instead of for loop

    3.27

    1. longest-common-prefix (easy)
      给一个都是string的array,去找最大的prefix,要注意所需要遍历到的最大index的位置,是不断被更新的,是动态的。

    2. squares-of-a-sorted-array (easy)
      主要是if else大赏,当需要maintain两个Pointer的时候,就该用while了。

    3. toeplitz-matrix (easy)
      matrix的行是matrix.length,列是matrix[0].length

    3.28

    1. hamming-distance (easy)
      奇数和偶数的区别,就是二进制形式最末一位是0还是1。另外右移,就是除以2,形式是a = a >> 1;

    2. merge-two-binary-trees (easy)
      这里merge的是val,而且要求从root开始merge,所以用preorder。递归的时候注意,return是要return很多次的,这样往左走到头了才能往别的方向跑。
      卡了很长时间的地方:if(right...)然后,不是else if(left...)而是if(left...)。 不要乱用else if。

    3. single-number (easy)
      从都是两个的重复的数中,找出单独的那个数。就是一个小trick,a^a=0。

    3.31

    1. increasing-order-search-tree (easy)
      把BST按照inorder重新排列成丿。
      要点一:newRoot.right = new TreeNode(root.val) 接续下一个Node的时候,我们要的只是root的value,而不能直接写root,因为那还包括人家自己的left,right指针
      要点二:一开始设一个dummy node,作为最终返回的结果。这样子我们就可以像链表一样自我推进,newRoot = newRoot.right;

    2.move-zeroes (easy)
    inplace地把0移到array右边,同时不影响非0元素的顺序。
    好方法:inplace的时候,就利用数组自己的index来存储,因为原数组可能含0,所以把非零数尽可能往数组的前面的Index堆积,再回头补上0就可以。

    3.valid-anagram (easy)
    这里要尝试考虑unicode characters的进阶:换成hashmap,但是需要自己设定一个0的基准数。(因为数组的优势是自己默认值就是0,这里要考虑同一个字符可能会不止一个)
    这里注意遍历的时候,map出来的值是Integer不是Int。

    相关文章

      网友评论

          本文标题:2019-03

          本文链接:https://www.haomeiwen.com/subject/jfnwpqtx.html