亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

leetcode explore 初級算法第四題: 找出不重復的列表

標簽:
Python

leetcode explore 初级算法第四题。原题链接:

题目分析

因为题目不是很长,这里把题目贴出来:

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true
Example 2:

Input: [1,2,3,4]
Output: false
Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

题目意思很简单,即如果整个列表是没有重复数字的,返回 False,否则返回 True

参考答案

这个题目本身并不难,因为也没有限制空间复杂度,用 Python 来解决尤其简单,我们可以使用 set 这种数据结构,参考代码如下:

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        snums = set(nums)
        return len(snums) != len(nums)

题目本身值得讲一讲的地方在于,这个题目涉及到面试经常会问到的一个题目,即:

Python 中如何对列表进行去重?

参考答案如下:

# 如果仅仅是去重
set('b', 'b', 'a', 'a', 'b', 'b', 'a'])

# 如果要保持顺序
# 第一种方法,也是最笨的方法
new_list = [] # 定义一个空的列表
for elem in slist:
    if elem not in new_list:  
        new_list.append(elem)

# 第一种方法可以用 reduce 来
from functools import reduce

#def f(x,y):
#    if y not in x:
#        return x + [y]
#    else:
#        return x

# 上面的等价于:
f = lambda x,y: x if y in x else x + [y]

print(list(reduce(f, [[], 1, 5, 4, 9, 3, 6, 9, 1, 5, 4, 3])))
print(list(reduce(f, [[],'b', 'b', 'a', 'a', 'b', 'b', 'a'])))

# 第二种方法,利用 key 来保证顺序
slist = ['b', 'b', 'a', 'a', 'b', 'b', 'a']
ll = list(set(slist))
ll.sort(key=slist.index)
return ll

# 第三种方法,利用 OrderedDict
from collections import OrderedDict

ordered_dict = OrderedDict.fromkeys(['b', 'b', 'a', 'a', 'b', 'b', 'a'])
list(ordered_dict)

此外,上面提到的第三种方法,在 python3.7 之后,dict 的效果就和 OrderedDict 的效果是一样的了,所以直接可以用 dict 来实现。

點擊查看更多內容
1人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消