Ritko Link: Rikko
You are given an integer array nums. Returns true if any value occurs at least twice in the array; returns false if every element in the array is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
input: nums = [1,2,3,4]
output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
hint:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
Sample code 1: [set deduplication]
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums) == len(set(nums)):
return False
else:
return True
Idea: Use set to deduplicate. If there are duplicate elements, the length of the list must be smaller than the length of the original list after deduplication, so it is enough to judge whether the lengths of the two are the same
Sample code 2: [Sorting]
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
j = 1
while j < len(nums):
if nums[j] == nums[j-1]:
return True
else:
j += 1
return False
Idea: Sort first, then judge whether two adjacent elements are equal, if they are equal, it means that there are duplicate elements
Note: code 2 is more time consuming than code !