1. 程式人生 > >leetcode簡單題81-100(python)

leetcode簡單題81-100(python)

387. First Unique Character in a String(e-81)-----------

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

389. Find the Difference(e-82)

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        sum1 = sum(map(ord, [c for c in s]))
        sum2 = sum(map(ord, [c for c in t]))
        return chr(sum2 - sum1)

400. Nth Digit(e-83)

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

class Solution(object):
    def findNthDigit(self, n):
        """
        :type n: int
        :rtype: int
        """
        """
        個位數:1-9,一共9個,共計9個數字
        2位數:10-99,一共90個,共計180個數字
        3位數:100-999,一共900個,共計270個數字
        4位數,1000-9999,一共9000個,共計36000個數字  36000=4*9*10**(4-1)
        ......
        """
        #第一步確定n是在幾位數裡,第二步是確定在幾位數的第幾位數字的第幾位
        #第一步
        digit=1#位數
        while n>digit*9*10**(digit-1):
            n-=digit*9*10**(digit-1)
            digit+=1
        #第二步
        a=int((n-1)/digit)#得到幾位數的第幾位數字
        b=int((n-1)%digit)#得到幾位數的第幾位數字的第幾位
        num=10**(digit-1)+a#得到第幾位數字是多少
        res=list(str(num))[b:b+1]#數字轉字元再轉列表把第幾位數的第幾位切出來
        return int(''.join(res))#列表轉字元再轉數字

401. Binary Watch(e-84)

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes(0-59).

Each LED represents a zero or one, with the least significant bit on the right

class Solution(object):
    def readBinaryWatch(self, num):
        """
        :type num: int
        :rtype: List[str]
        """
        ans=[]
        for i in range(0,12):
            for j in range(0,60):
                if (bin(i)+bin(j)).count("1") == num:
                    ans.append("%d:%0.2d"%(i, j))
                    
        return ans

404. Sum of Left Leaves(e-85)

Find the sum of all left leaves in a given binary tree.

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if root.left and not root.left.left and not root.left.right:
            return root.left.val + self.sumOfLeftLeaves(root.right)
        return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

405. Convert a Number to Hexadecimal(e-86)

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        d = {0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f"}
        ans = ""
        mask = 0xf0000000
        flag = False
        for i in xrange(0, 8):
            halfb = (num & mask) >> 28
            if halfb != 0:
                flag = True
            if flag:
                ans = ans + d[(num & mask) >> 28]
            num = num << 4
        if ans == "":
            return "0"
        return ans

409. Longest Palindrome(e-87)

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

class Solution(object):
    def longestPalindrome(self, s):
        ss = set(s)
        #print ss
        res = 0
        for i in ss:
            tmp = s.count(i)
            if tmp % 2 == 0:
                res += tmp
            else:
                if tmp > 1:
                    res += (tmp - 1)
                    tmp = 1
                if res%2 == 0:
                    res += 1
        return res

412. Fizz Buzz(e-88)

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res=[]
        for i in range(1,n+1):
            if i%3 == 0 and i%5 == 0:
                res.append("FizzBuzz")
            elif i%3==0 and i%5!=0:
                res.append("Fizz")
            elif i%3!=0 and i%5==0:
                res.append("Buzz")
            else:
                res.append("{}".format(i))
        return res

414. Third Maximum Number(e-89)

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a=set(nums)
        if len(a)<3: 
            return max(a)
        else: 
            a.remove(max(a))
            a.remove(max(a))
            return max(a)

415. Add Strings(e-90)--------

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

427. Construct Quad Tree(e-91)-------

We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.

Each node has another two boolean attributes : isLeaf and valisLeaf is true if and only if the node is a leaf node. The valattribute for a leaf node contains the value of the region it represents.

Your task is to use a quad tree to represent a given grid. The following example may help you understand the problem better:

Given the 8 x 8 grid below, we want to construct the corresponding quad tree:

429. N-ary Tree Level Order Traversal(e-92)-------

Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example, given a 3-ary tree:

 

 

We should return its level order traversal:

434. Number of Segments in a String(e-93)

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        return (len(s.split()))

437. Path Sum III(e-94)--------

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

438. Find All Anagrams in a String(e-95)

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

from collections import Counter
class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        sCount = Counter(s[:len(p) - 1])
        pCount = Counter(p)
        ans = []
        
        for i in range(len(p) - 1, len(s)):
            sCount[s[i]] += 1
            if sCount == pCount:
                ans.append(i - len(p) + 1)
            sCount[s[i - len(p) + 1]] -= 1
            if sCount[s[i - len(p) + 1]] == 0:
                del sCount[s[i - len(p) + 1]]
        return ans

441. Arranging Coins(e-96)

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

class Solution(object):
    def arrangeCoins(self, n):
        return int(((8*n + 1)**0.5 - 1)/2)
        
        

443. String Compression(e-97)

Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.

class Solution(object):
    def compress(self, chars):
        """
        :type chars: List[str]
        :rtype: int
        """
        n = len(chars) 
        cur = 0 # 當前字元的索引,用以壓縮原字串
        i = 0
        while i < n:
            j = i
            while j < n - 1 and chars[j] == chars[j+1]:# 找字元連續出現的次數
                j += 1
            chars[cur] = chars[i] # 記錄當前處理的字元
            cur += 1
            if i != j:
                times = str(j-i+1) # 將字元的次數寫入原串中
                tLen = len(times)
                for k in range(tLen):
                    chars[cur+k] = times[k]
                cur += tLen
            i = j + 1 # 處理下一個字元
        return cur

447. Number of Boomerangs(e-98)

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).

class Solution(object):
    def numberOfBoomerangs(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        ans=0
        for p1 in points:
            d={}
            for p2 in points:
                if p1!=p2:
                    dist=(p1[0] - p2[0]) ** 2 + (p1[1] - p2[1])**2
                    d[dist] = d.get(dist, 0) + 1
            for k in d:
                ans+=d[k]*(d[k]-1)
        return ans

448. Find All Numbers Disappeared in an Array(e-99)

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        news=range(1,len(nums)+1)
        return list(set(news) - set(nums))
        

453. Minimum Moves to Equal Array Elements(e-100)

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

class Solution(object):
    def minMoves(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return (sum(nums) - len(nums)*min(nums))