1. 程式人生 > >Leetcode簡單題1、7、9、13、14、20、21

Leetcode簡單題1、7、9、13、14、20、21

1.給定一個整數數列,找出其中和為特定值的那兩個數。
class Solution:
    def twoSum(self, nums, target):
        n = len(nums)
        for i in range(n):
            for j in range(i+1,n):
                temp = target - nums[i]
                print('temp',temp)
                if nums[j] == temp:
                    return i, j
7.給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
class Solution:
    def reverse(self, x):
        flag = 0
        if x < 0:
            x = -x
            flag = 1
        y = 0
        yu = x % 10
        chu = x // 10
        while chu!=0 or yu!=0:
            y = y*10+yu
            yu = chu%10
            chu = chu//10
        if y>2**31-1 or y<-2**31:
            return False
        if flag == 0:
            return y
        else:
            return -y
9.迴文數
class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        string = []
        if x < 0:
            return False
        while x:
            temp = x % 10
            string.append(temp)
            x = x // 10
        n = len(string)
        print(n)
        print(string)
        for i in range(n):
            n = n-1
            print("i:", string[i])
            print("n:", string[n])
            if string[i] != string[n]:
                return False
        return True
13.羅馬數字轉整數
class Solution:
    def romanToInt(self, s):
        sum = 0
        i = 0
        switch = {
            'I': 1,
            'V': 5,
            'X': 10,
            'L': 50,
            'C': 100,
            'D': 500,
            'M': 1000
        }
        for i in range(len(s)-1):
            # print("before:", i)
            # print(switch[s[i]])
            if switch[s[i]] < switch[s[i+1]]:
                sum -= switch[s[i]]
            else:
                sum += switch[s[i]]
            # print('after', i)
        sum += switch[s[len(s)-1]]
        return sum
14.最長公共字首
class Solution:
    def longestCommonPrefix(self, strs):
        if len(strs) == 0 or "" in strs:
            return ""
        if len(strs) == 1:
            return strs[0]
        ml = []
        for i in range(len(strs)):
            ml.append(len(strs[i]))
        ml = min(ml)
        # ml = min([len(x) for x in strs])
        end = 0
        while end < ml:
            for i in range(len(strs)-1):
                if strs[i][end] != strs[i+1][end]:
                    return strs[0][:end]
            end += 1
        return strs[0][:end]
20.有效括號
class Solution(object):
    def isValid(self, s):
        stack = []
        r = ""
        maps = {'(': ')', '[': ']', '{': '}'}
        if s is None or len(s) % 2 == 1:
            return False
        for i in s:
            if i == '(' or i == '[' or i == '{':
                stack.append(i)
            else:
                if not stack:
                    return False
                r = stack.pop()
                if (r == '(' and i == ')') or (r == '[' and i == ']') or (r == '{' and r == '}'):
                    continue
                else:
                    return False
        if len(stack) == 0:
            return True
        else:
            return False
21.合併兩個有序連結串列
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        # if not l1:
        #     return l2
        # if not l2:
        #     return l1
        p = ListNode(0)
        head = p
        while l1 and l2:
            if l1.val > l2.val:
                head.next = l2
                l2 = l2.next
            else:
                head.next = l1
                l1 = l1.next
            head = head.next
        if l1:
            head.next = l1
        if l2:
            head.next = l2
        return p.next
if __name__ == '__main__':
    h1 = ListNode(2)
    n1 = ListNode(3)
    n2 = ListNode(9)
    h1.next = n1
    n1.next = n2
    h2 = ListNode(3)
    m1 = ListNode(4)
    m2 = ListNode(7)
    h2.next = m1
    m1.next = m2
    t = Solution()
    res = t.mergeTwoLists(h1, h2)
    while res:
        print(res.val)
        res = res.next