Leetcode summary: some trick problem

Here list some problem, maybe, sometimes, hard to think the way to resolve, and summary here, when it comes to the right road, problem solution will become so elegant.

781. Rabbit in the forrest

#
# @lc app=leetcode id=781 lang=python
#
# [781] Rabbits in Forest
#
class Solution(object):
    def numRabbits(self, answers):
        """
        :type answers: List[int]
        :rtype: int
        """
        dic={}
        ret=0
        for ans in answers:
            if ans+1 not in dic or dic[ans+1]==0:
                ret+=ans+1
                dic[ans+1]=ans
            else:
                dic[ans+1]-=1

        return ret

60. Permutation Sequence

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

“123”
“132”
“213”
“231”
“312”
“321”
Given n and k, return the kth permutation sequence.

Note:

Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:

Input: n = 3, k = 3
Output: “213”
Example 2:

Input: n = 4, k = 9
Output: “2314”

#
# @lc app=leetcode id=60 lang=python
#
# [60] Permutation Sequence
#
class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        s="123456789"
        ret=""
        f=[1 for i in range(n)]

        for i in range(1,n):
            f[i]=f[i-1]*i
        
        k=k-1
        for i in range(n,0,-1):
            j=k/f[i-1]
            ret=ret+s[j]
            k=k%f[i-1]
            if j==len(s)-1:
                s=s[:j]
            else:
                s=s[:j]+s[j+1:]

        return ret

77. Combinations

Normally, we will using the DFS method, but here using stack is more efficient and more elegant.

class Solution(object):
    def combine(self, n, k):
        res = []
        stack = []
        x = 1
        while True:
            if len(stack) == k:
                res.append(stack[:])
            if len(stack) == k or x > n-k+len(stack)+1: 
            # here x>n also woks, but will have more operation, n-k+l+1 means check if have enough space to hold the max value in the current array
                if not stack:
                    return res
                x = stack.pop() + 1
            else:
                stack.append(x)
                x += 1

80. Remove Duplicates from Sorted Array II

using a trick to tranverse one time:
a slow index, a fast index

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i=0
        count=0
        
        for j in range(1,len(nums)):
            if nums[j]==nums[i]:
                count+=1
                if count<2:
                    i+=1
                    nums[i]=nums[j]
            else:
                i+=1
                count=0
                nums[i]=nums[j]
                
        return i+1

134. Gas Station

An explanation from discuss:

Proof to the first point: say there is a point C between A and B – that is A can reach C but cannot reach B. Since A cannot reach B, the gas collected between A and B is short of the cost. Starting from A, at the time when the car reaches C, it brings in gas >= 0, and the car still cannot reach B. Thus if the car just starts from C, it definitely cannot reach B.

Proof for the second point:
If there is only one gas station, it’s true.
If there are two gas stations a and b, and gas(a) cannot afford cost(a), i.e., gas(a) < cost(a), then gas(b) must be greater than cost(b), i.e., gas(b) > cost(b), since gas(a) + gas(b) > cost(a) + cost(b); so there must be a way too.
If there are three gas stations a, b, and c, where gas(a) < cost(a), i.e., we cannot travel from a to b directly, then:
either if gas(b) < cost(b), i.e., we cannot travel from b to c directly, then cost© > cost©, so we can start at c and travel to a; since gas(b) < cost(b), gas© + gas(a) must be greater than cost© + cost(a), so we can continue traveling from a to b. Key Point: this can be considered as there is one station at c’ with gas(c’) = gas© + gas(a) and the cost from c’ to b is cost(c’) = cost© + cost(a), and the problem reduces to a problem with two stations. This in turn becomes the problem with two stations above.
or if gas(b) >= cost(b), we can travel from b to c directly. Similar to the case above, this problem can reduce to a problem with two stations b’ and a, where gas(b’) = gas(b) + gas© and cost(b’) = cost(b) + cost©. Since gas(a) < cost(a), gas(b’) must be greater than cost(b’), so it’s solved too.
For problems with more stations, we can reduce them in a similar way. In fact, as seen above for the example of three stations, the problem of two stations can also reduce to the initial problem with one station.


class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        l=len(gas)
        sumall=0
        total=0
        s=0
        for i in range(l):
            sumall+=gas[i]-cost[i]
            total+=gas[i]-cost[i]
            if sumall<0:
                sumall=0
                #s+=1
                s=i+1  
                
        if total<0:
            return -1
        return s
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章