(Python)LeetCode 习题代码(部分)

1、关于特殊数字字符串等

1.1 Palindrome Number(#9)

题目翻译: 给定一个数字,要求判断这个数字是否为回文数字. 比如121就是回文数字,122就不是回文数字.

解题思路: 这道题很明显是一道数学题,计算一个数字是否是回文数字,我们其实就是将这个数字除以10,保留他的余数,下次将余数乘以10,加上这个数字再除以10的余数.

需要注意的点:

负数不是回文数字.
0是回文数字.
时间复杂度: logN

代码如下:

    def isPalindrome( x):
        if x<0 or (x!=0 and x%10==0):
            return False
        y =0
        m=x
        while x!=0:
            y = y * 10 + x % 10
            x = x//10
        return (y==m )

2、正则匹配

2.1 String to Integer (atoi)(#8)

题目要求:
1. 字串为空或者全是空格,返回0;
2. 字串的前缀空格需要忽略掉;
3. 忽略掉前缀空格后,遇到的第一个字符,如果是‘+’或‘-’号,继续往后读;如果是数字,则开始处理数字;如果不是前面的2种,返回0;
4. 处理数字的过程中,如果之后的字符非数字,就停止转换,返回当前值;
5. 在上述处理过程中,如果转换出的值超出了int型的范围,就返回int的最大值或最小值

代码如下:

   import re
    def myAtoi(self,str):
        s =str.strip()
        i = re.findall('(^[\+\-0]*\d+)\D*',s)
        try:
            result =''.join(i)
            Max_index = 2**31-1
            Min_index = -2**31
            if int(result)>Max_index:
                return Max_index
            elif int(result)<Min_index:
                return Min_index
            return int(result)

        except:
            return 0

3 集合List

3.1 Reverse Integer(#7)

题目要求:
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

代码如下:

def reverse(self, x):
        str='%d'%x
        a=[]
        if str[0]=='-':
            a.append("-")
            for m in list(range(-1, -len(str), -1)):
                a.append(str[m])
            result= int(''.join(a))
        else:
            for m in list(range(-1,-(len(str)+1),-1)):
                a.append(str[m])
            result = int(''.join(a))

        if result >2**31-1 or result <-2**31:
            return 0
        else:
            return result

3.2 ZigZag Conversion(#6)

题目如下:

扫描二维码关注公众号,回复: 1829030 查看本文章

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”

思路:
用下角标的方法判断太麻烦,而且会出现各种情况,尤其是最后一次循环以及第一行和最后一行特殊处理的情况,因此不合适。
采用List集合方法,新建List[“”,”“,”“,”“] (共nunRows个),将每个字符利用循环读一个存进一个,最后集体读出。

代码如下:

def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """ 

        if numRows == 1 or len(s)<numRows:
            return s 

        L=['']*numRows
        index,step = 0,1

        for x in s:
            L[index] +=x
            if index ==0:
                step = 1
            elif index ==numRows-1:
                step =-1
            index +=step
        return "".join(L)

3.3 Longest Common Prefix(#14)

Write a function to find the longest common prefix string amongst an array of strings.

返回一系列中字符串的最大公约数前缀。

最开始是用的list.pop()方法,但一直pop到最后一个列表元素时就不能在用这个方法,需要继续判断,比较麻烦。

另一种是利用min(map(len,strs))方法求得字符串最大公约数前缀的长度n。然后循环前n个字符判断是否相等。

另一种方法更加强大。利用了zip()、set()集合的特点,并利用了可选参数。代码如下:

def longestCommonPrefix( strs):

    sz, ret = zip(*strs), ""
    print(sz)
    for c in sz:
        print(c)
        if len(set(c)) > 1: break
        ret += c[0]
    print( ret)

longestCommonPrefix(["as","asd","asdff"])

# 其中sz是对应压缩的一种特殊格式,输出为<zip object at 0x000002113DC2F288>
# 需要对应读出

3.4 Remove Duplicates from Sorted Array(#26)

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

解析:删除掉重复的元素,并且不能生成额外的数组。最后生成数组的长度。

思路:利用前后的元素比较,相同就删掉,不同元素下标加一继续比较。
代码如下:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:
            return 0
        i,tmp=0,None
        while i <len(nums):
            if tmp!=nums[i]:
                tmp=nums[i]
                i=i+1
            else:
                del nums[i]
        return len(nums)

3.5 Remove Element(#27)

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.
解析:删除给定元素,并返回长度。不能产生额外空间。跟上一题类似。

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if len(nums)==0:
            return 0
        i=0
        while i<len(nums):
            if val!=nums[i]:
                i=i+1
            else:
                del nums[i]
        return len(nums)

3.6 Implement strStr()(#28)

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解析:当haystack 中包含needle 时,返回needle出现的下标。若不出现则返回-1
思路:遍历needle中的字符,判断与haystack第一个元素是否相同,若相同则继续遍历needle,若不同则删除haystack第一个元素,记录删除了几次,并让遍历needle的下标归回到0。循环。最后返回删除的次数。
代码如下:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(haystack)==0 and len(needle)==0:
            return 0
        if needle not in haystack:
            return -1
        i,j=0,0
        m = list(haystack)
        n=list(needle)
        while i < len(needle):
            if needle[i]!=m[i]:
                del m[0]
                j=j+1
                i=0
            else:
                i=i+1
        return j

4 字典 Dic

4.1 Two Sum(#1)

题目如下:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

返回下标

代码如下:

                           **python版本**
def twoSum(nums,target):
    if len(nums) <= 1:
        return False
    buff_dict = {}
    for i in range(len(nums)):
        if nums[i] in buff_dict:
            print([buff_dict[nums[i]], i+1])
            #return [buff_dict[nums[i]], i + 1]

        else:
            buff_dict[target - nums[i]] = i +1
                           **JAVA版本**
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result=new int[2];
        for(int i=0;i<nums.length;i++){
          for(int j=i+1;j<nums.length;j++){
              if (target==nums[i]+nums[j]){
                  result[0]=i;
                  result[1]=j;
                  return result;
              }     
          }
      }
        return result;
    }
}

4.2 Roman to Integer(#13 )

题目如下:
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

给定一个罗马数字,直接返回阿拉伯数字。

思想:
罗马数字的规则有很多,但是本题是默认输入为规范的罗马数字,只需直译过来就好,不用判断是否合乎规则。因此根据左减右加原则,可得到如下代码:

def romanToInt(s):
    roman_dic={'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    result = 0
    if len(s)>1:
        for i in range(len(s)-1):
            t=roman_dic[s[i]]
            if roman_dic[s[i]]<roman_dic[s[i+1]]:
                t=-roman_dic[s[i]]
            result=result+t
            print(roman_dic[s[i]])
        result=result+roman_dic[s[i+1]]
    elif len(s)==1:
        result=roman_dic[s]
    print(result)

romanToInt('MCMXCVI')

5 栈

5.1 Valid Parentheses(#20)

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

括号匹配

思路:如果正要入栈的是右括号,而栈顶元素不是能与之消去的相应左括号,那么该输入字符串一定是无效的。

代码如下:

class Solution(object):
    def isValid(self,s):
        """"
        :type s:str
        :rtype:bool
        """"
        a =[None]  //栈,其中len(a)==1,不是0
        parmap={')': '(', '}': '{', ']': '['}       
        for x  in s:
            if x in parmap:
                if parmap[x]!=a.pop():
                    return False
            else:
                a.append(x)
        return len(a)==1

6 链表

6.1 Merge Two Sorted Lists(#21)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题目解析: 合并两个已排序的链表,并重新排序。
例如:L1: 2->3->4->5
L2: 4->5->6->7
合并之后新链表为2->3->4->4->5->5->6->7
思路:将每个链表的最小值拿出来进行比较,三个链表的指针同时向后挪动。
代码如下:

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result=ListNode(0)
        tmp=result
        while l1!=None and l2!=None:
            if l1.val<=l2.val:
                tmp.next=l1     //赋值
                l1=l1.next   // 重新指向最小值
            else:
                tmp.next=l2
                l2=l2.next
            tmp=tmp.next   //指针后移为下一轮比较作准备
        if l1==None:
            tmp.next=l2
        else:
            tmp.next=l1
        return result.next

6.2 Remove Nth Node From End of List(#19)

Given a linked list, remove the nth node from the end of list and return its head.(倒数第n个数移走)

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
解题思路:利用双指针同时移动,两个指针间隔n
代码如下:

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        temp1=temp2=head
        for t in range(n):
            temp1=temp1.next
        if not temp1:
            return head.next
        while temp1.next:
            temp1=temp1.next
            temp2=temp2.next
        temp2.next=temp2.next.next
        return head

6.3 Swap Nodes in Pairs(#24)(递归)

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题目解析:
Alt text
指针的变化如图所示。现在已经将前两个变换,然后利用递归方法完成剩余的。

代码如下:

  class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next==None:
            return head
        tmp=head.next
        head.next=self.swapPairs(tmp.next)  //递归,受限完成34的变换,再完成12
        tmp.next=head
        return tmp

6.4 Length of Last Word(#58)

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = “Hello World”,
return 5.

题目解析:判断最后一个非空格字符的长度
代码如下:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        return (len(s.strip().split(" ")[-1]))

此代码利用了python的strip()方法,没有普遍意义。
方法2: 利用双指针的方法

        ls = len(s)
        slow = -1
        while slow>=-ls and s[slow]==" ":
            slow=slow-1
        fast = slow
        while fast>=-ls and s[fast]!=" ":
            fast=fast-1
        return (slow-fast)

第一个指针判断到非空格字符停止,然后将其赋值给fast,fast开始判断直到遇到空格停止。两个指针的差值就是所求的最后一个非空字符的长度。

猜你喜欢

转载自blog.csdn.net/huanghui147258369/article/details/64172698