leetcode practice - python3 (11)

48 篇文章 0 订阅
15 篇文章 0 订阅

338. Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.

思路:0->0, 1->1, 2->1, 3->2…
3&2 = 0b11 & 0b10 = 0b10 = 2
5&4 = 0b101 & 0b100 = 0b100 = 4
14&13 = 0b1110 & 0b1101 = 0b1100 = 12
x比 x & (x-1)多一个位1的bit

class Solution:
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        ans = [0] * (num + 1)
        for i in range(1, num+1):
            ans[i] = ans[i & (i-1)] + 1
        return ans

Beat 93.13% python3 2018-06-01

思路:0, 1, 2, 3 -> 4, 5, 6, 7都是多了最高位一个bit
0 ->
0, 1 ->
0, 1, 1, 2 ->
0, 1, 1, 2, 1, 2, 2, 3

class Solution:
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        ans = [0]
        while len(ans) < num+1:
            ans += [1 + n for n in ans]
        return ans[: num+1]

Beat 98.45% python3 2018-06-01

347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

思路:用defaultdict统计出现次数,用list统计各个次数的数字,按次数降序填充ans

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        d = collections.defaultdict(int)
        for n in nums:
            d[n] += 1

        counts = [[] for i in range(len(nums)+1)]
        for key in d:
            if d[key]:
                counts[d[key]].append(key)

        ans = []
        c = len(nums)
        while len(ans) < k:
            if counts[c]:
                ans += counts[c]
            c -= 1

        return ans[:k]

Beat 50.78% python3 2018-06-01

思路:使用python的Counter, most_common

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        counts = collections.Counter(nums).most_common()

        ans = []
        for c in counts:
            ans.append(c[0])
            if len(ans) == k:
                break;

        return ans

Beat 99.13% python3 2018-06-01

208. Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods.

Example:
Trie trie = new Trie();

trie.insert(“apple”);
trie.search(“apple”); // returns true
trie.search(“app”); // returns false
trie.startsWith(“app”); // returns true
trie.insert(“app”);
trie.search(“app”); // returns true
Note:

You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.

思路:defaultdict

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.children = collections.defaultdict(Trie)
        self.end = False


    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        node = self
        for c in word:
            node = node.children[c]
        node.end = True


    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self
        for c in word:
            if c not in node.children:
                return False
            node = node.children[c]

        return node.end


    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node = self
        for c in prefix:
            if c not in node.children:
                return False
            node = node.children[c]

        return True

# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

Beat 83.59% python3 2018-06-02

思路:dict

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}


    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        node = self.root
        for c in word:
            if c not in node:
                node[c] = {}
            node = node[c]
        node['end'] = True


    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
        for c in word:
            if c not in node:
                return False
            node = node[c]

        return 'end' in node


    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node = self.root
        for c in prefix:
            if c not in node:
                return False
            node = node[c]

        return True

# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

Beat 99.74% python3 2018-06-02

215. Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

思路:PriorityQueue

class Solution:
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        import queue
        pq = queue.PriorityQueue()
        for n in nums:
            pq.put(-n)

        ans = 0
        for i in range(k):
            ans = pq.get()
        return -ans

Beat 31.94% python3 2018-06-02

思路:heapq的nlargest

class Solution:
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        import heapq
        return heapq.nlargest(k, nums)[k-1]

Beat 99.44% python3 2018-06-02

238. Product of Array Except Self

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

class Solution:
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        ans = [1] * len(nums)

        current = 1
        for i in range(len(nums)):
            ans[i] = current
            current *= nums[i]

        current = 1
        for i in range(len(nums)-1, -1, -1):
            ans[i] *= current
            current *= nums[i]

        return ans

Beat 99.84% python3 2018-06-02

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值