Leetcode 算法题03

来源:互联网 发布:域名反向解析作用 编辑:程序博客网 时间:2024/05/16 19:41

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: TrueExplanation: 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: FalseExplanation: 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: 3Explanation: 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 keydef 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: 5Output: TrueExplanation:The binary representation of 5 is: 101

Example 2:

Input: 7Output: FalseExplanation:The binary representation of 7 is: 111.

Example 3:

Input: 11Output: FalseExplanation:The binary representation of 11 is: 1011.

Example 4:

Input: 10Output: TrueExplanation: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


原创粉丝点击