LeetCode_Simple_1

点击这里,阅读效果更好

以下代码均在python3中运行

217、存在重复元素

  • 原题连接
  • 给定一个整数数组,判断是否存在重复元素。如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
  • 示例 1:输入: [1,2,3,1],输出: true
  • 示例 2:输入: [1,2,3,4],输出: false
  • 示例 3:输入: [1,1,1,3,3,4,3,2,4,2],输出: true
def ContainDuplicate(nums):
    if len(set(nums))!= len(nums):
        return True
    else:
        return False
nums = [1,2,3,1]
ContainDuplicate(nums)
True
nums = [1,2,3,4]
ContainDuplicate(nums)
False
a=[1,2,3,1]
a[1]
2

219、存在重复元素II

  • 原题连接
  • 注:个人认为题目有问题,输入为[1,0,1,1],k=1,输出应该为false
  • 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
  • 示例 1:输入: nums = [1,2,3,1], k = 3,输出: true
  • 示例 2:输入: nums = [1,0,1,1], k = 1,输出: true
  • 示例 3:输入: nums = [1,2,3,1,2,3], k = 2,输出: false
def containsNearbyDuplicate(nums, k):
    if len(nums)<2:
        return False
    
    length_temp = []
    length = len(nums)
    for i in range(length):
        for j in range(length):
            if nums[i] == nums[j]:
                length_temp.append(abs(i-j))
                
    if max(length_temp) == k:
        return True
    else:
        return False
a = [1,0,1,1]
b = [1,2,3,1]
c = [1,2,3,1,2,3]
d = [1,2,1,1,1,3,2,2,2,3,1]
containsNearbyDuplicate(a, k=1)
False
containsNearbyDuplicate(a, k=3)
True
containsNearbyDuplicate(b, k=3)
True
containsNearbyDuplicate(c, k=2)
False
containsNearbyDuplicate(d, k=10)
True

283、移动零

  • 原题链接
  • 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
  • 示例: 输入: [0,1,0,3,12],输出: [1,3,12,0,0]
  • 说明:必须在原数组上操作,不能拷贝额外的数组。尽量减少操作次数。
#方法1:
def MoveZeroes(nums):
    j = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[j], nums[i] = nums[i],nums[j]
            j += 1
a = [0,0,1,3,12,0]
MoveZeroes(a)
a
[1, 3, 12, 0, 0, 0]
#方法2:
def MoveZeroes(nums):
    for i in range(len(nums)-1,-1,-1):
        if nums[i] ==0:
            del nums[i]
            nums.append(0)
a=[0,0,1,2,0,3,0]
MoveZeroes(a)
a
[1, 2, 3, 0, 0, 0, 0]

812、最大三角形面积

  • 原题链接
  • 给定包含多个点的集合,从其中取三个点组成三角形,返回能组成的最大三角形的面积。
  • 示例:输入: points = [[0,0],[0,1],[1,0],[0,2],[2,0]],输出: 2
    def largestTriangleArea(points):
        """
        :type points: List[List[int]]
        :rtype: float
        """
        area = []
        for a in points:
            for b in points:
                for c in points:
                    area.append (0.5*(a[0]*b[1]+b[0]*c[1]+c[0]*a[1]
                                             -a[0]*c[1]-b[0]*a[1] - c[0]*b[1]))
        max_area = max(area)   
        return max_area
points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
largestTriangleArea(points)
2.0

自定义求平方根

  • 牛顿法
def My_sqrt(n):
    root = n/2
    for i in range(20):
        root = (1/2)*(root + n/root)
    return root
#为了验证精确度,对比实验
import math
math.sqrt(25)
5.0
My_sqrt(25)
5.0
My_sqrt(5000)==math.sqrt(5000)
True

821、字符最短距离

  • 原题连接
  • 问题:给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。
  • 示例:输入: S = “loveleetcode”, C = ‘e’,输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
def shortestToChar(S,C):
        """
        :type S: str
        :type C: str
        :rtype: List[int]
        """
        list_C = []   #所有字符C的索引值组成的列表
        for i in range(len(S)):
            if S[i] == C:
                list_C.append(i)
        result = []
        for i in range(len(S)):
            d = min(abs(i-d) for d in list_C)
            result.append(d)
        return result
shortestToChar("loveleetcode",'e')
[3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
'''用时最短的算法'''
def shortestToChar(S, C):
        """
        :type S: str
        :type C: str
        :rtype: List[int]
        """
        record = []
        res = []
        for i in range(0,len(S),1):
            if S[i] == C:
                record.append(i)#找到所有字符C的索引
                
        for i in range(0,record[0],1):
            res.append(record[0] - i)
        res.append(0)
        for i in range(0,len(record) - 1,1):
            mid = (record[i+1] + record[i]) // 2
            for j in range(record[i] + 1,mid + 1,1):
                res.append(j - record[i])
            for j in range(mid + 1,record[i+1],1):
                res.append(record[i+1] - j)
            res.append(0)
        for i in range(record[len(record) - 1] + 1,len(S),1):
            res.append(i -record[len(record) - 1])
        return res
shortestToChar("loveleetcode",'e')
[3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

832、反转图像

  • 原题链接
  • 问题:给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
    水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
    反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。
  • 示例:输入: [[1,1,0],[1,0,1],[0,0,0]], 输出: [[1,0,0],[0,1,0],[1,1,1]]
def flipAndInvertImage(A):
    """
    :type A: List[List[int]]
    :rtype: List[List[int]]
    """
    for col in A:
        col.reverse()
        for i in range(len(col)):
            #col[i] = col[i]^1
            col[i] = 1-col[i]
    return A
flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]])
[[1, 0, 0], [0, 1, 0], [1, 1, 1]]

852、山脉数组的峰值索引

  • 原题链接
  • 问题:我们把符合下列属性的数组 A 称作山脉:
    A.length >= 3
    存在 0 < i < A.length - 1 使得A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length - 1]
    给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length - 1] 的 i 的值。
  • 示例:输入:[0,1,0]输出:1。输入:[0,2,1,0]
    输出:1
def peakIndexInMountainArray( A):
        """
        :type A: List[int]
        :rtype: int
        """
        # return A.index(max(A))
        for i in range(1,len(A)-1):
            if A[i] > A[i+1]:
                return i
peakIndexInMountainArray([0,1,2,3,7,8,9,5,4,0])
6

867、转置矩阵

  • 原题链接
  • 问题:给定一个矩阵 A, 返回 A 的转置矩阵。矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
  • 示例:输入:[[1,2,3],[4,5,6],[7,8,9]]输出:[[1,4,7],[2,5,8],[3,6,9]]。输入:[[1,2,3],[4,5,6]]输出:[[1,4],[2,5],[3,6]]
def transpose(A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        result = []
        for i in range(len(A[0])):
            child_list = []
            for item in A:
                child_list.extend([item[i]])
            result.append(child_list)
        return result
A = [[1,2,3],[4,5,6],[7,8,9]]
transpose(A)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  • 注意:上述代码中child_list.extend([item[i]])不可以是child_list.extend(item[i]),否则会报’int’ object is not iterable.
  • 如下面的测试:
List = []
List.extend(1)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-53-17d9c1d9c01d> in <module>()
      1 List = []
----> 2 List.extend(1)


TypeError: 'int' object is not iterable
List.extend([1])
List
[1]
'''他人算法'''
def transpose( A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        A[::]=zip(*A)
        return A
A = [[1,2,3],[4,5,6]]
transpose(A)
[(1, 4), (2, 5), (3, 6)]
zip(*A)
<zip at 0x1488ee0>
list(zip(*A))
[(1, 2, 3), (4, 5, 6)]
list(zip(*zip(*A)))
[(1, 4), (2, 5), (3, 6)]
def transpose( A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        return list(zip(*zip(*A)))
transpose(A)
[(1, 4), (2, 5), (3, 6)]
def transpose( A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        A[:] = map(list,zip(*A))
        return A
A = [[1,2,3],[4,5,6]]
transpose(A)
[[1, 4], [2, 5], [3, 6]]
ord('a')
97
ord('g')-97
6

804、唯一摩尔斯密码词

  • 原题链接
  • 问题:国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: “a” 对应 “.-”, “b” 对应 “-…”, “c” 对应 “-.-.”, 等等。为了方便,所有26个英文字母对应摩尔斯密码表如下:[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,“cab” 可以写成 “-.-…–…”,(即 “-.-.” + “-…” + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。返回我们可以获得所有词不同单词翻译的数量。
  • 示例:输入: words = [“gin”, “zen”, “gig”, “msg”],输出: 2
  • 解释:
    各单词翻译如下:
    “gin” -> “–…-.”
    “zen” -> “–…-.”
    “gig” -> “–…--.”
    “msg” -> “–…--.”
def uniqueMorseRepresentations(words):
        """
        :type words: List[str]
        :rtype: int
        """
        key = [".-","-...","-.-.","-..",".","..-.","--.","....",
               "..",".---","-.-",".-..","--","-.","---",".--.","--.-",
               ".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        result = []
        for word in words:
            morse = ''
            for ch in word:
                morse += key[ord(ch)-97]           
            result.append(morse)
        return len(set(result))
words =["rwjje","aittjje","auyyn","lqtktn","lmjwn"]
result = uniqueMorseRepresentations(words)
result
1
a=[1,3,4,2]
a.sort()
a
[1, 2, 3, 4]
sorted(a)
[1, 2, 3, 4]
a
[1, 2, 3, 4]
sorted(a,reverse=True)
[4, 3, 2, 1]

896、单调数列

  • 原题链接
  • 问题:如果数组是单调递增或单调递减的,那么它是单调的。如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。当给定的数组 A 是单调数组时返回 true,否则返回 false。
  • 示例:输入:[1,2,2,3],输出:true。输入:[6,5,4,4],输出:true。输入:[1,3,2],输出:false
def isMonotonic(A):
        """
        :type A: List[int]
        :rtype: bool
        """
        first = 0
        last = len(A)-1
        Not_found = True
        if len(A)<=2:
            return True
        #假定是升序
        elif A[0] < A[last]:
            while first < last and Not_found:
                if A[first] <= A[first+1] and A[last] >= A[last-1]:
                    first += 1
                    last -= 1
                else:
                    Not_found = False
            return Not_found
        #假定是降序
        elif A[0] > A[last]:
            while first < last and Not_found:
                if A[first] >= A[first+1] and A[last] <= A[last-1]:
                    first += 1
                    last -= 1
                else:
                    Not_found = False
            return Not_found
        else:
            result = True
            for i in range(1,len(A)-1):
                if A[i]!=A[0]:
                    result = False
                    break
            return result
A1 = [1,1,2,3,4,4,6,5,6]
A2 = [1,1,1,2,2,2,2]
A3 = [3,3,1,1,0]
isMonotonic(A1)
False
isMonotonic(A2)
True
isMonotonic(A3)
True
  • 竟然打败了100%的用户,哈哈,有点小意外!

  • 再看个表现不错的例子:很精妙

def isMonotonic(A):
        return all(x >= y for x, y in zip(A, A[1:])) or all(x <= y for x, y in zip(A, A[1:]))
isMonotonic(A1)
False

922、按奇偶排序数组

  • 原题链接
  • 问题:给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
    对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
    你可以返回任何满足上述条件的数组作为答案。
  • 示例:输入:[4,2,5,7],输出:[4,5,2,7],解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
def sortArrayByParityII( A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        #A.sort()
        even = 0
        odd = 1
        result = [None] * len(A)
        for index in range(len(A)):
            if A[index]%2 == 0:#偶数
                result[ou] = A[index]
                even += 2
            else:
                result[ji] = A[index]
                odd += 2           
        return result
a = [5,2,4,3,6,1]
sortBY(a)
[2, 5, 4, 3, 6, 1]
  • 一开始审题错误,以为还要按照升序或者降序排序,然后再按位置排序。结果只按位置,注释掉即可,测试用例减少了40ms,打败了98.8%的用户
  • 别人的优秀代码:
def sortArrayByParityII(A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        l1 = list(filter(lambda x: x % 2 == 0, A))
        l2 = list(filter(lambda x: x % 2 == 1, A))
        res = []
        for i in range(len(l1)):
            res.append(l1[i])
            res.append(l2[i])
        return res
a = [3,2,4,5,1,6]
sortArrayByParityII(a)
[2, 3, 4, 5, 6, 1]
  • 此题倒是没有看到比较新颖的做法,基本上都是先把奇数偶数分离出来,然后插入到指定位置

  • filter(fun,iterable)和map(func,iterable)函数在使用上差不多

66、加一

  • 原题链接

  • 问题:给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
    最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
    你可以假设除了整数 0 之外,这个整数不会以零开头。

  • 示例 1:输入: [1,2,3],输出: [1,2,4],解释: 输入数组表示数字 123。

def plusOne(digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        string = ''
        for item in digits:
            string += str(item)
        string = str(int(string)+1)       
        return [int(x) for x in string]
a = [1,2,3]
plusOne(a)
[1, 2, 4]
'''有一点提升'''
def plusOne(digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if digits[-1] < 9:
            digits[-1] += 1
            return digits
        else:
            string = ''
            for item in digits:
                string += str(item)
            string = str(int(string)+1)       
            return [int(x) for x in string]
a = [1,2,3,9]
plusOne(a)
[1, 2, 4, 0]
a[0:0] = [1]
a
[1, 1, 1, 1, 1, 2, 3, 9]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值