当前位置:网站首页>判断数组中是否存在重复元素
判断数组中是否存在重复元素
2022-07-02 06:36:00 【迷途~知返】
数组
原理
python的使用方法
列表中元素的排列
sort方法
给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
解题思路
- 对现有数组进行排序,
- 对数组中的元素进行按位比较
#第一版代码:
class Solution(object):
def containsDuplicate(self, nums):
""" :type nums: List[int] :rtype: bool """
#1. 对列表中的元素进行排序
nums.sort()
print "nums", nums
n = len(nums)
print n
i = 0
# while i <= n:
# if nums[i] == nums[i+1]:
# return True
# else:
# return False
for i in range(n-1):
if nums[i] == nums[i+1]:
return True
else:
return False
i = i + 1
报错信息如上:循环变量设置错误,循环变量的值始终为0,当前两位元素相同时,可返回为true,当列表中只有一个元素中,无法进行输出,
修改后的代码如下:
class Solution(object):
def containsDuplicate(self, nums):
""" :type nums: List[int] :rtype: bool """
nums.sort()
n = len(nums)
if n <=1:
return False
else:
for i in range(n-1):
# print "i", i
if nums[i] == nums[i+1]:
return True
return False
循环变量设置有误,i的值始终为0,此时元素无法移位进行比较,只会比较第一和第二位,不会比较到后两位元素
class Solution(object):
def containsDuplicate(self, nums):
""" :type nums: List[int] :rtype: bool """
nums.sort()
n = len(nums)
for i in range(n-1):
if nums[i] == nums[i+1]:
return True
i = i + 1
return False
当前的 时间复杂度为:O(nlogn),空间复杂度为1
解法二:
哈希表
class Solution(object):
def containsDuplicate(self, nums):
""" :type nums: List[int] :rtype: bool """
#方法二:哈希表
visted = set()
for num in nums:
if num in visted:
return True
visted.add(num)
return False
时间复杂度:O(N),空间复杂度O(N)
个人见解:以空间换时间的方式进行
边栏推荐
- Data insertion in C language
- 2837xd code generation - stateflow (3)
- What is call / cc- What is call/cc?
- 【Unity3D】制作进度条——让Image同时具有Filled和Sliced的功能
- Introduction and prevention of penetration test
- 【教程】如何让VisualStudio的HelpViewer帮助文档独立运行
- It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
- 虛幻AI藍圖基礎筆記(萬字整理)
- This article takes you to learn in detail what is fiber to home FTTH
- webUI自动化学习
猜你喜欢

【UE5】蓝图制作简单地雷教程

ESLint 报错

Illusion -- Animation blueprint, state machine production, character walking, running and jumping action

Summary of demand R & D process nodes and key outputs

Edge computing accelerates live video scenes: clearer, smoother, and more real-time

2837xd code generation module learning (4) -- idle_ task、Simulink Coder
![[unreal] animation notes of the scene](/img/97/dafde0377b7c4337e1775db64ba6a4.png)
[unreal] animation notes of the scene

【虚幻】过场动画笔记

Sil/pil test of matlab code generation

虛幻AI藍圖基礎筆記(萬字整理)
随机推荐
MySQL -- time zone / connector / driver type
2837xd code generation - stateflow (2)
High level application of SQL statements in MySQL database (II)
AutoCAD - layer Linetype
How to handle error logic gracefully
MySQL transaction
阿里云SLS日志服务
go语言入门
Project practice, redis cluster technology learning (16)
Brief analysis of edgedb architecture
VLAN experiment
UE5——AI追逐(藍圖、行為樹)
C language: making barrels
Eslint reports an error
【教程】如何让VisualStudio的HelpViewer帮助文档独立运行
2837xd code generation - Supplement (2)
UE4夜间打光笔记
【虚幻】过场动画笔记
阿里云短信服务
Blender石头雕刻