Leetcode 算法题21


9Palindrome Number

判断一个数是否是回文数(要求不用额外的内存,但我觉得没什么意义)

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        return str(x) == str(x)[::-1]
大神的代码:还是用了临时变量啊

class Solution:
    # @param x, an integer
    # @return a boolean
    def isPalindrome(self, x):
        if x < 0:
            return False

        ranger = 1
        while x / ranger >= 10:
            ranger *= 10

        while x:
            left = x / ranger
            right = x % 10
            if left != right:
                return False
            
            x = (x % ranger) / 10
            ranger /= 100

        return True

26 Remove Duplicates from Sorted Array

in-place去除列表中的重复元素,返回一个长度l,这个列表的前l个元素没有重复

我的代码:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        last = nums[0]
        index = 1
        for i in nums[1:]:
            if i == last:
                del nums[index]
            else:
                last = i
                index += 1
        return index


374 Guess Number Higher or Lower
使用它给的内置函数猜一个数

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):

class Solution(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        start = 0
        end = n+1
        while end - start > 1:
            guessnum = (start+end)//2
            if guess(guessnum) == -1:
                end = guessnum
            elif guess(guessnum) == 1:
                start = guessnum
            else:
                return guessnum
其中start,end用列表元素表示会更快
大神的代码:

    def guessNumber(self, n):
        class C: __getitem__ = lambda _, i: -guess(i)
        return bisect.bisect(C(), -1, 1, n)
还有一个有趣的指定变量

    def guessNumber(self, n):
        lo, hi = 1, n
        while lo < hi:
            mid = (lo + hi) / 2
            lo, hi = ((mid, mid), (mid+1, hi), (lo, mid-1))[guess(mid)]
        return lo


441 Arranging Coins

直接上例子:

Example 1:

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

Example 2:

n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the 4th row is incomplete, we return 3.
我的代码:

class Solution:
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        last = 0
        i = 1
        while i + last <= n:
            last += i
            i += 1
        return i-1
大神的代码:笨笨的方法还是太慢了

return math.floor( 0.5 * (math.sqrt(1 + 8 * n) - 1.0) )

443 String Compression

字符串压缩:

Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

Example 2:

Input:
["a"]

Output:
Return 1, and the first 1 characters of the input array should be: ["a"]

Explanation:
Nothing is replaced.

Example 3:

Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]

Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].

Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
我的代码:

class Solution:
    def compress(self, chars):
        """
        :type chars: List[str]
        :rtype: int
        """
        last = chars[0]
        strnum = 1
        count = 1
        for s in chars[1:].copy()+[0]:
            if s == last:
                count += 1
                del chars[strnum]  #用del会拖慢很多
            elif count == 1:
                strnum += 1
                last = s
            elif count != 1:
                for i in str(count):
                    chars.insert(strnum,i)
                    strnum += 1
                count = 1
                strnum += 1
                last = s
        return len(chars)
比较取巧的办法,至少我觉得这不是真的in-place:

class Solution(object):
    def compress(self, c):
        flips = [(c[0], 0)] + [(c[i], i) for i in range(1, len(c)) if c[i] != c[i - 1]] + [(None, len(c))]
        chunks = [(b[0], a[1] - b[1]) for (a, b) in zip(flips[1:], flips)]
        compressed = reduce(lambda a, b: (a + [b[0]] + (list(str(b[1])) if (b[1] > 1) else [])), chunks, [])
        c[:len(compressed)] = compressed
        return len(compressed)
另一个版本:用直接赋值而非删除元素

class Solution(object):
    def compress(self, chars):
        left = i = 0
        while i < len(chars):
            char, length = chars[i], 1
            while (i + 1) < len(chars) and char == chars[i + 1]:
                length, i = length + 1, i + 1
            chars[left] = char
            if length > 1:
                len_str = str(length)
                chars[left + 1:left + 1 + len(len_str)] = len_str
                left += len(len_str)
            left, i = left + 1, i + 1
        return left








9 Palindrome Number
26 Remove Duplicates from Sorted Array
441 Arranging Coins
443 String Compression
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值