Leetcode 算法題03

575. Distribute Candies

輸入一個含偶數個數字的列表,兩個人均勻地分其中的數字,輸出其中能分到最多不同數字的個數

原本的代碼提交的時候報了超時錯誤,應該是迭代太複雜了

超時的代碼:遍歷次數太多

class Solution(object):
    def distributeCandies(self, candies):
        """
        :type candies: List[int]
        :rtype: int
        """
        anslist = []
        for i in candies:
            if i not in anslist:
                anslist.append(i)
            else:
                pass
        if len(anslist) <= len(candies)//2:
            return len(anslist)
        else:
            return len(candies)//2
思考後的代碼:先將輸入排序,依次遍歷一遍就可以了

class Solution(object):
    def distributeCandies(self, candies):
        """
        :type candies: List[int]
        :rtype: int
        """
        candies.sort()
        anslist = [candies[0]]
        for i in candies:
            if i == anslist[-1]:
                continue
            else:
                anslist.append(i)
        if len(anslist) <= (len(candies)//2):  #這個判斷語句可以用min()來代替
            return len(anslist)
        else:
            return len(candies)//2
        
大神的代碼:理解set集合的概念和運用!!,min函數也要熟練

def distributeCandies(self, candies):
    return min(len(candies) / 2, len(set(candies)))


521. Longest Uncommon Subsequence I

輸入兩個字符串,兩個字符串中存在一個最長的子字符串string,string只存在一個字符串不存在另一個字符串中,求輸出這個子字符串的長度不存在則輸出-1

這道題真的很扯,看懂了就是求較大的字符串長度,兩個字符串一樣時輸出-1,這道題踩的人有1000+

我的代碼:

class Solution(object):
    def findLUSlength(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: int
        """
        return max(len(a),len(b)) if a != b else -1

717. 1-bit and 2-bit Characters

給定一個最後一位爲0的序列,規定只能由11或10或0組成,求安規定劃分後,最後的0是否爲單獨的

Example 1:

Input: 
bits = [1, 0, 0]
Output: True
Explanation: 
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.

Example 2:

Input: 
bits = [1, 1, 1, 0]
Output: False
Explanation: 
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
我的代碼,
class Solution(object):
    def isOneBitCharacter(self, bits):
        """
        :type bits: List[int]
        :rtype: bool
        """
        while len(bits) > 1:
            if bits[0] == 1:
                bits.pop(0)
                bits.pop(0)
            elif bits[0] == 0:
                bits.pop(0)        
        return bits == [0]      #做個copy可能會好一點
大神的代碼:比我的長,但是用索引來找感覺比我的好

    if not bits: return False
    n = len(bits)
    
    index = 0
    while index < n:
        if index == n-1 : return True
        if bits[index] == 1: 
            index += 2              
        else: index += 1
    return False

485. Max Consecutive Ones

輸入一個含0和1的序列,求其中連續最多的1的個數

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.
我的代碼:想到啥寫啥,反正都是遍歷一遍,做個表

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        list = []
        count = 0
        for i in nums:
            if i == 1:
                count += 1
            else:
                list.append(count)
                count = 0
	list.append(count)
        return max(list)
大神用了單獨的ans代替list,用max函數判斷是否替換:ans = max(ans, cnt),其實多想想也能想到


136. Single Number

輸入一個序列,其中每個數字出現2次,除了一個數字,找到這個數

我的代碼:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        index = 0
        while index+1 < len(nums):
            if nums[index] == nums[index+1]:
                index += 2
            else:
                return nums[index]
        return nums[index]
大神給出五個版本:

def singleNumber1(self, nums):
    dic = {}
    for num in nums:
        dic[num] = dic.get(num, 0)+1
    for key, val in dic.items():
        if val == 1:
            return key

def singleNumber2(self, nums):
    res = 0
    for num in nums:
        res ^= num
    return res
    
def singleNumber3(self, nums):
    return 2*sum(set(nums))-sum(nums)
    
def singleNumber4(self, nums):
    return reduce(lambda x, y: x ^ y, nums)
    
def singleNumber(self, nums):
    return reduce(operator.xor, nums)


693. Binary Number with Alternating Bits

給定正整數,檢查它是否具有交替位:即,如果兩個相鄰位總是具有不同的值。

Example 1:

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.

Example 3:

Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.

Example 4:

Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
我的代碼
class Solution(object):
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        anslist = str(bin(n)[2:]).split('10')
        for i in range(len(anslist)-1):
            if anslist[i] :
                return False
        return anslist[-1] == '' or anslist[-1] == '1'
        
大神給出了很多思路:給出幾個我看得懂的,代碼沒有python版的

1.取消bit位;2.填充bit位;3.用正則表達式;4.用‘00’‘11’in n

292. Nim Game

兩個人移石子,一次移1-3個,輸入石子個數,求第一個是否能贏

很簡單的問題,想清楚就可以了

class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n % 4 != 0


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章