PIXNET Logo登入

CONY的世界

跳到主文

在這裡我不是要向大家講述我的生活,只是想留著一些回憶

部落格全站分類:生活綜合

  • 相簿
  • 部落格
  • 留言
  • 名片
  • 7月 29 週六 201712:49
  • Leetcode Backtracking 211, 79 @Python

211. Add and Search Word - Data structure design

 
Design a data structure that supports the following two operations:
 
(繼續閱讀...)
文章標籤

angledark0123 發表在 痞客邦 留言(0) 人氣(60)

  • 個人分類:Algorithm medium
▲top
  • 7月 27 週四 201713:40
  • Leetcode Dynamic Programmin 523, 464 @Python

523. Continuous Subarray Sum

 
Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.
(繼續閱讀...)
文章標籤

angledark0123 發表在 痞客邦 留言(0) 人氣(67)

  • 個人分類:Algorithm medium
▲top
  • 7月 25 週二 201722:56
  • Leetcode Divide and Conquer 240, 215 @Python

240. Search a 2D Matrix II

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
(繼續閱讀...)
文章標籤

angledark0123 發表在 痞客邦 留言(0) 人氣(42)

  • 個人分類:Algorithm medium
▲top
  • 7月 25 週二 201709:29
  • Leetcode Binary Search 50, 222 @Python

50. Pow(x, n)
Implement pow(x, n).

Success:
56 ms, beats 14.53 % of python submissions
先用最簡單的方式做
(繼續閱讀...)
文章標籤

angledark0123 發表在 痞客邦 留言(0) 人氣(24)

  • 個人分類:Algorithm medium
▲top
  • 7月 24 週一 201715:39
  • Leetcode String 151, @Python

151. Reverse Words in a String
Given an input string, reverse the string word by word.
 For example,
Given s = "the sky is blue",
return "blue is sky the".
(繼續閱讀...)
文章標籤

angledark0123 發表在 痞客邦 留言(0) 人氣(19)

  • 個人分類:Algorithm medium
▲top
  • 7月 20 週四 201715:47
  • Leetcode Two pointers 18,209 @Python

18. 4Sum
 

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

 
Success:
我一開始想到的方法比較慢,先固定two sum 然後再用left, right 找到剩餘符合 target value 的值
當然two sum 還是要考慮到不能重複,所以才會在for loop 一開始有個醜醜的判斷式來決定到底要不要做
1008 ms, beats 36.12 % of python submissions
(繼續閱讀...)
文章標籤

angledark0123 發表在 痞客邦 留言(0) 人氣(101)

  • 個人分類:Algorithm medium
▲top
  • 7月 19 週三 201716:52
  • Leetcode Math 8, 29 @Python

8. String to Integer (atoi)
 
Implement atoi to convert a string to an integer.
(繼續閱讀...)
文章標籤

angledark0123 發表在 痞客邦 留言(0) 人氣(9)

  • 個人分類:Algorithm medium
▲top
  • 7月 13 週四 201719:27
  • Leetcode Hashtable 166, 3 @Python

166. Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,

  • Given numerator = 1, denominator = 2, return "0.5".

  • Given numerator = 2, denominator = 1, return "2".

  • Given numerator = 2, denominator = 3, return "0.(6)".


  •  Success:
     42ms, beats 47.06 % of python submissions
     在寫出這題的過程當中發現Time Limit Exceeded應該是因為有無限迴圈在.......
    所以之前的fail....應該不是因為太慢被擋掉,而是因為邏輯就錯了(No~~~~~)
    後來這題邏輯改一改就出來了
    依照hint 裡面提到的,只要餘數開始重複後,除數也會開始重複,所以我就用了dict (hash table) 來記載餘數的值和對應到除數的位置
    一但之前有記載過,除術也從之前的位子開始repeat
    然後這題要注意的是負數的處理,依照wiki提到的(https://zh.wikipedia.org/wiki/余数)
    Python语言定义的除法中,不能整除的情况下,余数与除数同号,例如 (−42) / (−5) 表达为
    −42 = 8×(−5) + (−2)

    而 42 / (-5) 则表达为
    42 = (−8)×(−5) + 2

    所以有沒有負號會在一開始做判斷,之後都用abs()後的正值去做計算
    class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
    """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
    result = ''
    module = abs(numerator)/abs(denominator)
    if ((numerator> 0 and denominator < 0) or (numerator < 0 and denominator > 0)):
    result += "-"
    result += str(module)
    denominator,numerator = abs(denominator),abs(numerator)
    remainder = numerator%denominator
    if remainder != 0:
    result +='.'
    decimal = ''
    dict = {}
    while remainder != 0:
    if dict.has_key(remainder):
    result+=decimal[:dict[remainder]] + '('+str(decimal[dict[remainder]:]) + ')'
    break
    else:
    dict[remainder] = len(decimal)
    while 10*remainder < denominator:
    remainder*= 10
    decimal+='0'
    dict[remainder] = len(decimal)
    decimal+=str(10*remainder / denominator)
    remainder = 10*remainder % denominator
    if remainder == 0:
    result += decimal
    return result

     不過我這種寫法太醜不夠簡潔,來改寫成官方分享裡思路跟我一樣的簡潔版
    分別是 1.把decimal 拿掉  2.算好的先return,讓後面要處理的case變少 
    class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
    """
            :type numerator: int
            :type denominator: int
            :rtype: str
            """
    res=''
    if ((numerator> 0 and denominator < 0) or (numerator < 0 and denominator > 0)):
    res='-'
    numerator, denominator = abs(numerator), abs(denominator)
    res += str(numerator/denominator)
    numerator %= denominator
    if numerator == 0:
    return res
    res+='.'
    index, dict = len(res),{}
    while numerator != 0:
    if numerator not in dict.keys():
    dict[numerator] = index
    else:
    index = dict[numerator]
    res = res[:index]+"("+res[index:]+")"
    return res
    numerator*=10
    res += str(numerator/denominator)
    numerator %=denominator
    index+=1
    return res

     再貼另外一個大神的做法,不過因為跟我思路不太同,就先不實作了
    class Solution:
    # @return a string
    def fractionToDecimal(self, numerator, denominator):
    n, remainder = divmod(abs(numerator), abs(denominator))
    sign = '-' if numerator*denominator < 0 else ''
    result = [sign+str(n), '.']
    stack = []
    while remainder not in stack:
    stack.append(remainder)
    n, remainder = divmod(remainder*10, abs(denominator))
    result.append(str(n))

    idx = stack.index(remainder)
    result.insert(idx+2, '(')
    result.append(')')
    return ''.join(result).replace('(0)', '').rstrip('.')

     3. Longest Substring Without Repeating Characters

     

    Given a string, find the length of the longest substring without repeating characters.


    Examples:


    Given "abcabcbb", the answer is "abc", which the length is 3.


    Given "bbbbb", the answer is "b", with the length of 1.


    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequenceand not a substring.


     Success:


    92ms, beats 77.14 % of python submissions


    這題也是看官方解,用loop 和 start 來尋找不重複的sunstring


    一但遇到重複的char(已存在dic裡面)就要把start reset 到重複字元的下一個位置算起(因為一個字元至多只能出現一次)


    class Solution(object):
    def lengthOfLongestSubstring(self, s):
    """
            :type s: str
            :rtype: int
            """
    start= maxlength = 0
    Used = {}
    for i in range(len(s)):
    if Used.has_key(s[i]) and start <= Used[s[i]]:
    start = Used[s[i]]+1
    else:
    maxlength = max(maxlength, i-start+1)

    Used[s[i]]=i

    return maxlength

     


     



     
    (繼續閱讀...)
    文章標籤

    angledark0123 發表在 痞客邦 留言(0) 人氣(25)

    • 個人分類:Algorithm medium
    ▲top
    • 7月 12 週三 201713:04
    • Leetcode Array 442,15 @Python

    442. Find All Duplicates in an Array

    Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
    Find all the elements that appear twice in this array.
    Could you do it without extra space and in O(n) runtime?
     
    Example:
    Input:
    [4,3,2,7,8,2,3,1]

    Output:
    [2,3]

     Success: 本來的做法update在github裡面,採用先sort在比對的方式,不過performance不好,所以跑去看論壇裡的解法
    這題最快的人是用set寫,但是我覺得多開一個seen set這種做法應該不行,因為多用了extra space啊
    自己實作論壇裡我認為可行的方法,發現一個有趣的現象,我理解後重寫成的版本(399 ms),發現沒有原版本快,明明只差在< 和 >= ,不知道是不是跟access nums的行數有關係
    class Solution(object):
    def findDuplicates(self, nums):
    """
            :type nums: List[int]
            :rtype: List[int]
            """
    result = [];
    for x in nums:
    if nums[abs(x)-1] < 0:
    result.append(abs(x))
    else:
    nums[abs(x)-1] *= -1
    return result

    原版本(309 ms)
    class Solution(object):
    def findDuplicates(self, nums):
    """
            :type nums: List[int]
            :rtype: List[int]
            """
    ret = []
    for n in nums:
    if nums[abs(n) - 1] >= 0:
    nums[abs(n) - 1] *= -1
    else:
    ret.append(abs(n))
    return ret
    Fail:
    1. Time Limit Exceeded ,list.count() complexity O( nlogn )
    (繼續閱讀...)
    文章標籤

    angledark0123 發表在 痞客邦 留言(0) 人氣(23)

    • 個人分類:Algorithm medium
    ▲top
    • 6月 28 週三 201718:05
    • 2017 Algo HW3 Search(Binary Input)

    同樣是看code學習,把同班同學好的code拿出來看,不懂的筆記在這裡
     
    1. 如何有效率free vector memory
    因為用clear() 本身只是把element 清掉,但是空間並不會減少,有人主張用resize,不過更好的是用 temporary vector swap 
    (繼續閱讀...)
    文章標籤

    angledark0123 發表在 痞客邦 留言(0) 人氣(59)

    • 個人分類:學習
    ▲top
    «1...45661»

    個人資訊

    angledark0123
    暱稱:
    angledark0123
    分類:
    生活綜合
    好友:
    累積中
    地區:

    Top Posts

    • (16,627)什麼是Library(函式庫,大陸稱庫)
    • (863)我不知道風是在哪一個方向吹 徐志摩
    • (397)「大考大玩,小考小玩」的真實意義
    • (330)台北Mei’s Tea Bar ~好吃又特別的蘋果鬆餅
    • (265)yuv player 實作筆記
    • (162)寫程式語言人的痛(同感)
    • (133)何其芳〈夢中道路〉
    • (9)兩天一夜台北遊 part1 -元定食
    • (3)告訴你我在忙什麼
    • (1)多事之際

    文章分類

    toggle leetcode (3)
    • Algorithm medium (32)
    • easy (5)
    • hard (6)
    • google (1)
    • 拜家 (4)
    • 學習 (102)
    • 生活隨筆 (49)
    • 旅遊 (16)
    • 美食 (9)
    • 未分類文章 (1)

    最新文章

    • Leetcode Tree,Linkedlist 114 @ Java
    • Leetcode DP 764 @ Java
    • Leetcode Greedy 316 @ Java
    • Leetcode DP 140 @Java
    • Google CodeJam I/O for women 2/17- Graph-Centrist
    • Leetcode contest-2/17- BFS 785 @ Java
    • Leetcode Math 670 @Java
    • Leetcode Graph 269 @Java
    • Leetcode BFS 127 @ Java
    • Leetcode UnionFind 261 @Java

    最新留言

    • [24/08/12] 訪客 於文章「減重整理...」留言:
      瘦身要有效最重要的是提升自身代謝力 唯有代謝提高後,又...
    • [23/09/23] 新飛Hsinfei 於文章「最近英文課一波三折...」留言:
      都是為了連假!辛苦的補班英文該怎麼說?連假英文呢? http...
    • [22/04/27] 訪客 於文章「Create customized MP...」留言:
      原本在搜尋引擎找出一堆 Blog 文章,不知哪幾篇值得花時間...
    • [20/12/17] 哈 於文章「Leetcode Tree,Linked...」留言:
      爛...
    • [17/09/18] 老菜 於文章「Win7上灌vc6...」留言:
      您好,請問您還有FileTool這個補丁嗎?MicroSof...
    • [17/08/19] Tim Feng 於文章「Leetcode Stack 71,40...」留言:
      你好,我最近在學python,分析各位先賢們的專案。從200...
    • [16/11/09] Blake Hung 於文章「C/C++之指標 (pointer),參...」留言:
      非常詳盡,謝謝!...
    • [16/06/18] 路人 於文章「什麼是Library(函式庫,大陸稱庫)...」留言:
      黃色字很不清楚,不容易看。...
    • [15/04/20] 訪客 於文章「vim附件:cscope+ctag 使用...」留言:
      Ctrl+/ 再按s 表示:cs find s命令 ==>C...
    • [14/03/20] 射手白馬 於文章「心情雜記...」發表了一則私密留言

    文章精選

    文章搜尋

    誰來我家

    參觀人氣

    • 本日人氣:
    • 累積人氣: