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: 

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

134. Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
 
紀錄這題我一開始想到的就是想找扣最多當最後,然後向後找正值當起頭
結果很難寫.....就去解答了
這題用到蠻重要的一個觀念
When sum(i, j) < 0, start = i + 1

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

134. Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
 
紀錄這題我一開始想到的就是想找扣最多當最後,然後向後找正值當起頭
結果很難寫.....就去解答了
這題用到蠻重要的一個觀念
When sum(i, j) < 0, start = i + 1

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

71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

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

211. Add and Search Word - Data structure design

 
Design a data structure that supports the following two operations:
 

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

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) 人氣()

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) 人氣()

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

Success:
56 ms, beats 14.53 % of python submissions
先用最簡單的方式做

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

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) 人氣()

18. 4Sum
 

Given an array S of n integers, are there elements abc, 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) 人氣()

8. String to Integer (atoi)
 
Implement atoi to convert a string to an integer.

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

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) 人氣()

    Blog Stats
    ⚠️

    成人內容提醒

    本部落格內容僅限年滿十八歲者瀏覽。
    若您未滿十八歲,請立即離開。

    已滿十八歲者,亦請勿將內容提供給未成年人士。