Leetcode(page1)_easy

目录

 

1. Two Sum(两个数求和)

7. Reverse Integer(倒序整数)

13. Roman to Integer(罗马数字转换为整数)

14. Longest Common Prefix(公共最长前缀)

20. Valid Parentheses(有效的括号)

21. Merge Two Sorted Lists(合并两个有序的list)

26. Remove Duplicates from Sorted Array(从有序数组中移除重复值)

27. Remove Element

28. Implement strStr()

35. Search Insert Position

38. Count and Say


1. Two Sum(两个数求和)

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, and you may not use the same element twice.

给出一个整数数组,返回和为给定值的两个整数的索引。

Example:

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

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

第一种思路是:可以借助于Python中的字典来解决这个问题,首先我们定义一个空字典,然后遍历数组,如果数组中的值在字典中直接输出其在字典中的位置和当前值的索引,否则直接将其对应的值(也就是目标值减去其自身)加入字典中,并令其值为当前索引。即整体思路是将某个值的补(此处指目标值减去其自身)及其索引存入字典中,然后当遍历到其补值时,直接输出字典中对应的值和其索引。(说的可能有点啰嗦,大家直接自己动手试一下便可理解)

class Solution:
    def twoSum(self, nums: 'List[int]', target: int) -> 'List[int]':
        dicti = {}
        for i, n in enumerate(nums):
            if n in dicti:
                return [dicti[n],i]
            dicti[target-n] = i

第二种思路是:直接两个循环进行遍历。

class Solution:
    def twoSum(self, nums: 'List[int]', target: int) -> 'List[int]':
        length = len(nums)
        for i in range(length):
            for j in range(i+1,length):
                if nums[i] + nums[j]==target:
                    return [i,j]

7. Reverse Integer(倒序整数)

Given a 32-bit signed integer, reverse digits of an integer.(给定一个有符号的32位整数,返回倒置的数字)

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^{^{31}}2^{_{31}}-1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

这里需要注意的是数据的范围,不仅仅是输入的数据范围在[-2^{^{31}}2^{_{31}}-1],输出的数据也在这个范围,否则会出错

我在这里的思路是将数据先转换为字符,然后利用字符进行倒置s[::-1]是对s进行倒序

class Solution:
    def reverse(self, x: int) -> int:
        min_ = -2**31
        max_ = 2**31 - 1
        if x > min_ and x < max_:
            s = str(x)
            length = len(s)
            if s[0] == '-':
                s = s[1::]
                s = s[::-1]
                s = '-'+s
            else:
                s = s[::-1]
            if int(s)>min_ and int(s)<max_:
                return int(s)
            else:
                return 0
        else:
            return 0

9. Palindrome Number(回文数)

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

第一种思路:用字符串来解决

class Solution:
    def isPalindrome(self, x: int) -> bool:
        s = str(x)
        length = len(s)
        t = 0
        for i in range(round(length/2)):
            if s[i]==s[length-1-i]:
                t = 1+t
        if t == round(length/2):
            return True
        else:
            return False

第二种思路:不用字符串,即用数学的方法来求出有几位整数,然后分别将每一位放在一个数组中的对应位置,最后判断数组的元素是否满足回文数的要求。

class Solution:
    def isPalindrome(self, x: int) -> bool:
        l = []
        t = 0
        if x < 0:
            return False
        if x == 0:
            return True
        else:
            while x/10 != 0:
                l.append(x%10)
                x = int(x/10)
            length = len(l)
        for i in range(round(length/2)):
            if l[i]==l[length-1-i]:
                t = t + 1
            else:
                return False
        if t == round(length/2):
            return True
        else:
            return False

13. Roman to Integer(罗马数字转换为整数)

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

在解决这道题时我们可以运用字典,将罗马数字与其对应的整数以键值对的方式保存在字典中,然后遍历输入的罗马数字找寻其在字典中对应的整数。这里需要注意的是数字的范围。

class Solution:
    def romanToInt(self, s: str) -> int:
        dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        dic_d = {'IV':4, 'IX':9, 'XL':40, 'XC':90, 'CD':400, 'CM':900}
        length = len(s)
        i = 0
        inte = 0
        while i <length:
            j = i + 1
            if j <length:
                t = s[i] + s[j]
                if t in dic_d:
                    inte = inte + dic_d[t]
                    i = i + 2
                else:
                    inte = inte + dic[s[i]]
                    i = i + 1
            else:
                inte = inte + dic[s[i]]
                i = i + 1
        if inte >= 1 and inte <= 39999:
            return inte
        else:
            return False

14. Longest Common Prefix(公共最长前缀)

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

此题用到字符串的一些用法,首先找出字符串中最小的字符串的长度“len(min(strs,key=len))”,然后再遍历字符串的每一个首字符并存进list_中,判断list_的元素是否相同“len(set(list_))==1”

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        lengths = len(strs)
        t = 0
        flag = 0
        if lengths==0:
            flag = 0
        else:
            mini = len(min(strs,key=len))#查找str中最小的长度
            for i in range(mini):
                list_ = []
                for j in range(lengths):
                    list_.append(strs[j][i])
                if len(set(list_))==1:
                    t = t + 1
                    flag = 1
                else:
                    flag = 0
                    break
        if t == 0 and flag == 0:
            return ""
        else:
            return strs[0][0:t]

20. Valid Parentheses(有效的括号)

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

思路一:这个代码比较少直接假设这些括号在所给的字符串中并且将其用空代替,逐个查找,这是我在网上看到的思路,但是我不太容易想到这种。这里还有第二种思路,首先遍历整个字符串s,将左括号依次加入一个list中,接着再pop出一个并和后续的比较是否匹配。

class Solution:
    def isValid(self, s: str) -> bool:
        while "()" in s or "{}" in s or '[]' in s:
            s = s.replace("()", "").replace('{}', "").replace('[]', "")
        return s == ''
class Solution:
    def isValid(self, s: str) -> bool:
        output = []
        last_s = ""
        if len(s)==1:
            return False
        else:
            for i in s:
                if i == "(" or i == "{" or i =="[":
                    output.append(i)
                else:
                    if len(output)>0:
                        last_s = output.pop()
                    if i == ")" and last_s != "(":
                        return False
                    if i == "}" and last_s != "{":
                        return False
                    if i == "]" and last_s != "[":
                        return False
            if len(output)==0:
                return True
            else:
                return False

21. Merge Two Sorted Lists(合并两个有序的list)

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

思路:和数据结构中的链表一样,注意的是要head=head.next

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        head = ListNode(0)
        New_list = head
        while l1 != None and l2 != None:
            if l1.val > l2.val:
                head.next = l2
                l2 = l2.next
            else:
                head.next = l1
                l1 = l1.next
            head = head.next
            
        if l2 != None:
            head.next = l2
        elif l1 != None:
            head.next = l1
        return New_list.next  

26. Remove Duplicates from Sorted Array(从有序数组中移除重复值)

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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 returned length.

思路:

此题是直接在nums数组上进行修改,先从第一个元素开始遍历,如果第一个元素在后面的元素中出现,则删除第一个元素,并且数组总长度减一,如果没有在后面元素中重复出现则对下一个元素进行判断,直至结束,此算法思想简单但是用时较长。

class Solution:
    def removeDuplicates(self, nums: 'List[int]') -> int:
        numsLen = len(nums)
        i = 0
        while i < numsLen:
            temp_n = nums[i]
            if temp_n in nums[i+1:]:
                del nums[i]
                numsLen -= 1
            else:
                i += 1
        length = len(nums)
        return length

27. Remove Element

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

Example:(即将val从nums中移除)

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length

思路:此题的思路同26.从第一个元素开始查找是否与val相等,如果相等便删除,否则继续向后寻找。此思路简单相比于其他代码也比较快。

class Solution27:
    def removeElement(nums: 'List[int]', val: 'int') -> int:
        numsLen = len(nums)
        i = 0
        while i < numsLen:
            if nums[i] == val:
                del nums[i]
                numsLen -= 1
            else:
                i += 1
        return len(nums)   

28. Implement strStr()

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Input: haystack = "hello", needle = "ll"
Output: 2

思路:一定要读对题意。题中是说needle(而不是needle中的第一个元素)在haystack第一次出现的位置。并且后面说当needle为空时输出0。

首先要判断needle是否为空,即其长度是否为0,如果为0输出0,否则判断needle是否在haystack中,可以用循环的方式来一次对haystack中的needle长度个字符进行判断。

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if haystack == needle == "":
            return 0
        str1Len = len(haystack)
        str2Len = len(needle)
        while str2Len != 0:
            if needle in haystack:
                for i in range(str1Len):
                    if haystack[i:str2Len+i] == needle:
                        return i
            else:
                return -1
        return 0
        

35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

Example:

Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 7
Output: 4

思路:注意,这里说明如果target不在nums中则需要直接输出最后添加的一个位置即可。这里需要用到一个while循环,首先是当target在nums中的情况。

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        i = 0
        while i < len(nums):
            if nums[i] >= target:
                return i
            i += 1
        return i

38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。

思路:此时要注意n=4时输出为'1211',里面有3个1,1个2千万不要在n=5时输出3112,而是输出'111221',也就是下面第二个for 循环里的第一个if 语句可以控制。

class Solution38:
    def countAndSay(self, n: int) -> str:
        if n == 1:
            return '1'
        s = '1'
        for i in range(2,n + 1):
            res = ''
            count = 1
            for j in range(1,len(s)):
                if s[j - 1] == s[j]:
                    count += 1
                else:
                    res += str(count) + s[j - 1]
                    count = 1
            res += str(count) + s[-1]
            s = res
        return s

参考:

1.https://leetcode.com/problemset/all/

2.https://blog.csdn.net/qq_38575545/article/details/84999614

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值