这些题目最重要的是 结果

小聪明最重要

定义三个指针 最前面的用作迭代循环

反转链表(迭代循环 ,3指针,爷爷领路,爸爸认爹)

  1. class Solution:
  2. def reverseList(self, head: ListNode) -> ListNode:
  3. if head is None:
  4. return head
  5. if head.next is None:
  6. return head
  7. if head.next.next is None:
  8. r = head.next
  9. head.next = None
  10. r.next = head
  11. return r
  12. l = head
  13. mid = head.next
  14. r = head.next.next
  15. #先把第一步移动了
  16. l.next = None
  17. while True:
  18. if r.next is None:
  19. #移动到最后
  20. mid.next = l
  21. r.next = mid
  22. return r
  23. #排序移动
  24. mid.next = l
  25. print(mid)
  26. l = mid
  27. mid = r
  28. r = r.next

链表的中间结点

  1. class Solution:
  2. def middleNode(self, head: ListNode) -> ListNode:
  3. mid = head
  4. end = head
  5. while True:
  6. if end is None or end.next is None:
  7. return mid
  8. end = end.next.next
  9. mid = mid.next

367. 有效的完全平方数

输入:num = 16
输出:true

  1. class Solution:
  2. def isPerfectSquare(self, num: int) -> bool:
  3. i = 1;
  4. while True:
  5. print(i)
  6. n = i * i
  7. print(n)
  8. i = i + 1
  9. if n == num:
  10. return True
  11. if n > num:
  12. return False

整数反转(转字符串 转数字)

输入:x = 123
输出:321

  1. def reverse(self, x: int) -> int:
  2. is_negative = False
  3. if x < 0:
  4. is_negative = True
  5. x = abs(x)
  6. string = str(x)
  7. string = string[::-1]
  8. num = 0
  9. if is_negative:
  10. num = 0 - int(string)
  11. else:
  12. num = int(string)
  13. if num <= 2147483647 and num >= -2147483648 :
  14. return num
  15. else:
  16. return 0

回文数

  1. class Solution:
  2. def isPalindrome(self, x: int) -> bool:
  3. if x < 0:
  4. return False
  5. str_a = str(x)
  6. str_re = str_a[::-1]
  7. if str_a == str_re:
  8. return True
  9. else:
  10. return False

最后一个单词的长度(hello world)

  1. class Solution:
  2. def lengthOfLastWord(self, s: str) -> int:
  3. if s.strip() == "":
  4. return 0
  5. list_data = s.split()
  6. ss = list_data[len(list_data) - 1]
  7. return len(ss)

**

实现 strStr()

输入:haystack = “hello”, needle = “ll”
输出:2

  1. def strStr(self, haystack: str, needle: str) -> int:
  2. return haystack.find(needle)

剑指 Offer 03. 数组中重复的数字

输入:[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3

  1. class Solution:
  2. def findRepeatNumber(self, nums: List[int]) -> int:
  3. nums.sort()
  4. for index in range(0,len(nums)):
  5. if nums[index + 1] == nums[index]:
  6. return nums[index]

977. 有序数组的平方

输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]

  1. class Solution:
  2. def sortedSquares(self, nums: List[int]) -> List[int]:
  3. for index in range(len(nums)):
  4. nums[index] = nums[index] * nums[index]
  5. nums.sort()
  6. return nums

704. 二分查找

给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。

  1. class Solution:
  2. def search(self, nums: List[int], target: int) -> int:
  3. for index in range(len(nums)):
  4. if nums[index] == target:
  5. return index
  6. return -1
  7. class Solution:
  8. def search(self, nums: List[int], target: int) -> int:
  9. left, right = 0, len(nums) - 1
  10. while left <= right:
  11. pivot = left + (right - left) // 2
  12. if nums[pivot] == target:
  13. return pivot
  14. if target < nums[pivot]:
  15. right = pivot - 1
  16. else:
  17. left = pivot + 1
  18. return -1

. 两个数组的交集

给定两个数组,编写一个函数来计算它们的交集。


示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

  1. class Solution:
  2. def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
  3. list = []
  4. for no in nums1:
  5. if no in nums2 and no not in list:
  6. list.append(no)
  7. return list

有效的括号

给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        map = {')':'(',']':'[','}':'{'}
        for char in s :
            if char in map.values():
                stack.append(char)
            elif not stack or  map.get(char) != stack.pop() :
                return False

        return not stack

    //这样也是可以的
    elif len(stack) == 0 or  map.get(char) != stack.pop() :

344. 反转字符串

输入:[“h”,”e”,”l”,”l”,”o”]
输出:[“o”,”l”,”l”,”e”,”h”]

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        s.reverse()

217. 存在重复元素

输入: [1,2,3,1]
输出: true

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        setData = set()

        for n in nums:
            if n in setData:
                return True
            else:
                setData.add(n)

        return False

3的幂

给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。

整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3x

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        i = 1
        if n == 1:
            return True
        while True:
            i = i * 3
            if n == i:
                return True
            if i > n:
                return False

242. 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = “anagram”, t = “nagaram”
输出: true

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if sorted(s) == sorted(t):
            return True
        else:
            return False

237. 删除链表中的节点

难度简单892
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点。传入函数的唯一参数为 要被删除的节点
如何让当前一个节点消失 ,让下一个结点变成自己
这道题细思极恐:如何让自己在世界上消失,但又不死? —— 将自己完全变成另一个人,再杀了那个人就行了。

class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val =  node.next.val
        node.next = node.next.next

合并两个有序数组

输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
输出:[1,2,2,3,5,6]

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        for index in range(len(nums2)):
            nums1[len(nums1)- 1 - index] = nums2[index]

        return nums1.sort()

172. 阶乘后的零

难度简单452
给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。

class Solution:
    def trailingZeroes(self, n: int) -> int:
        no = 1
        for i in range(1,n + 1):
            no = i * no
        no_str = str(no)
        no_str = no_str[::-1]
        b = 0
        for char in no_str:
            if char == "0":
                b = b + 1
            else:
                break


        return b

268. 丢失的数字

输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        nums.sort()
        if nums[0] != 0:
            return 0
        if nums[-1] != len(nums):
            return len(nums)
        for index in range(len(nums)):
            if nums[index + 1] -  nums[index ] != 1:
                return nums[index ] + 1

191. 位1的个数

输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。

class Solution:
    def hammingWeight(self, n: int) -> int:

        b = 0
        while True:
            if n == 0:
                return b
            n = n & (n-1)
            b = b + 1

70. 爬楼梯

class Solution:
    mapData = {}
    def climb(self,m):
        if m == 1:
            return 1
        if m == 2:
            return 2
        if m in self.mapData.keys():
            return self.mapData.get(m)
        stage = self.climb(m-1) + self.climb(m-2)
        self.mapData[m] = stage
        return stage
    def climbStairs(self, n: int) -> int:
        return self.climb(n)

169. 多数元素

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        index = int(len(nums)/2)
        return nums[index]

14. 最长公共前缀

输入:strs = [“flower”,”flow”,”flight”]
输出:“fl”

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 1:
            return strs[0]

        short_letter = ""
        length = 0
        for str in strs:
            if len(str) == 0:
                return ""
            elif length != 0 and length > len(str):
                length = len(str)
                short_letter = str
            elif length == 0:
                length = len(str)
                short_letter = str

        if len(short_letter) == 0 :
            return ""

        for index in range(len(short_letter)):
            for str in strs:
                if str[index] == short_letter[index]:
                    continue
                else :
                    return short_letter[0:index]
        return short_letter