Leetcode 算法题01


现在没有数据结构的知识直接转机器学习去面试真的太难了,很多这种机器学习的岗位无论笔试面试都有很多数据结构的知识,有空也要做做数据结构的知识梳理。

从今天开始做Leetcode的算法题,以难度排序,由易到难,简单的时候一天多做一些,一周休息一天,使用python语言,期间看裘宗燕的《数据结构与算法 Python语言描述》,主要目的是能熟练使用python并熟悉基本的数据结构,为面试做准备。


461. Hamming Distance

两个整数转化为二进制后,按位不同的个数,输入0<x,y<2^31

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

我的代码:

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        d = '00000000000000000000000000000000'
        a=bin(x)[2:]
        b=bin(y)[2:]
        xbin = d[:-len(a)]+a
        ybin = d[:-len(b)]+b
        distance = 0
        for i in range(32):
            if xbin[i] != ybin[i]:
                distance += 1
        return distance
大神的代码:

class Solution(object):
    def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
	return bin(x^y).count('1')



657. Judge Route Circle

初始有一个机器人在座标(0,0)的位置,给出一个移动顺序的序列,如果机器人回到原点则输出True,移动指令分别为:'R','L','U','D'

Example 1:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false
我的代码:

本来想初始化一个座标并进行移动计算,后来想到上面第一题大神的回答,稍微想了一下。

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        return moves.count('R') == moves.count('L') and  moves.count('U') == moves.count('D')



617. Merge Two Binary Trees

树的合并

Example 1:

Input: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
Output: 
Merged tree:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7
这道题因为完全没接触过树的知识,想了很久也没做出来,基础实在太差了,就看了一下讨论,做了出来,要理解递归与self的意义

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if t1 == None and t2 == None:
            return None
        elif t1 == None:
            return t2
        elif t2 == None:
            return t1
        else:
            root = TreeNode(t1.val+t2.val)
            root.left = self.mergeTrees(t1.left,t2.left)
            root.right = self.mergeTrees(t1.right,t2.right)
        return root

561. Array Partition I

给出一个列表,两两分组为(a1,b1),(a2,b2)...使min(ai,bi)的和尽可能大

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
我的代码:总之就是将列表排序后隔一个取一个数累加

class Solution:
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        ans = 0
        for i in range(len(nums)//2):
            ans += nums[i*2]
        return ans
大神的代码:切片的使用

class Solution(object):

    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(sorted(nums)[::2])

476. Number Complement
给一个数,转为二进制后按位取反,输出结果的十进制

我的代码:replace那里忘记赋值了,以为和sort()函数一样用了就自动赋值了

class Solution(object):
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        string = str(bin(num))[2:]
        string = string.replace('0','a')
        string = string.replace('1','0')
        string = string.replace('a','1')
        return int(string,2)
大神的代码:用N个1按位异或

class Solution(object):
    def findComplement(self, num):
        i = 1
        while i <= num:
            i = i << 1
        return (i - 1) ^ num


500. Keyboard Row

给含多个单词的列表,排除其中所有字母不在键盘一行内的单词

Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
我的代码:
class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        line=['QWERTYUIOP','ASDFGHJKL','ZXCVBNM']
        ans = list(words)
        for word in words:
            flag = (word[0].upper() in line[0])+2*(word[0].upper() in line[1])
            +3*(word[0].upper() in line[2])
            for i in word.upper():
                if i not in line[flag-1]:
                    ans.pop(ans.index(word))
                    break
        return ans 
大神的代码:使用了正则表达式

def findWords(self, words):
    return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)  #(?i) 表示所在位置右侧的表达式开启忽略大小写模式


557. Reverse Words in a String III

输入一个句子,将句子中每个单词的字幕顺序置反并输出

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
我的代码:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        wordlist=s.split()
        anslist=[]
        ans=""
        for word in wordlist:
            anslist.append(word[::-1])
        for i in anslist:
            ans += ' '
            ans += i
        return ans[1:]
大神的代码:熟悉join函数,join函数只能用于字符串格式
def reverseWords(self, s):
    return ' '.join(s.split()[::-1])[::-1]




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